PHP mysqli insert_id()関数
例-オブジェクト指向スタイル
「Persons」テーブルに自動生成されたidフィールドがあると想定します。最後のクエリからIDを返します。
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$mysqli -> query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', 33)");
// Print auto-generated id
echo
"New record has id: " . $mysqli -> insert_id;
$mysqli -> close();
?>
下部にある手続き型の例を見てください。
定義と使用法
mysqli_insert_id()関数は、最後のクエリからのID(AUTO_INCREMENTで生成された)を返します。
構文
オブジェクト指向スタイル:
$mysqli ->
insert_id
手続き型:
mysqli_insert_id(connection)
パラメータ値
Parameter | Description |
---|---|
connection | Required. Specifies the MySQL connection to use |
技術的な詳細
戻り値: | 最後のクエリによって更新されたAUTO_INCREMENTフィールドの値を表す整数。更新がないか、AUTO_INCREMENTフィールドがない場合は、ゼロを返します |
---|---|
PHPバージョン: | 5歳以上 |
例-手続き型
「Persons」テーブルに自動生成されたidフィールドがあると想定します。最後のクエリからIDを返します。
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
mysqli_query($con, "INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', 33)");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
❮PHPMySQLiリファレンス