mysqli_stmt::$insert_id

mysqli_stmt_insert_id

直近に実行したステートメントで生成された AUTO_INCREMENT カラムの値を返す

説明

オブジェクト指向型

intstring$mysqli_stmt->insert_id;

手続き型

intstring mysqli_stmt_insert_id(mysqli_stmt $statement)

AUTO_INCREMENT 属性を持つカラムがあるテーブル上での INSERT 文や UPDATE 文が生成した ID を返します。 複数行の INSERT 文の場合、 自動生成されて挿入に成功した最初の値を返します。 LAST_INSERT_ID(expr) を AUTO_INCREMENT の値の設定に使った場合や、 UPDATE 文で使った場合は、 expr の値を返します。

ステートメントが AUTO_INCREMENT の値を変更しなかった場合、 0 を返します。

パラメータ

stmt
手続き型のみ: mysqli_stmt_init が返す mysqli_stmt オブジェクト。

戻り値

ステートメントが更新した AUTO_INCREMENT フィールドの値を返します。ステートメントがまだ実行されていない場合や、 AUTO_INCREMENT の値を更新しなかった場合はゼロを返します。

この値はステートメントオブジェクトに固有のものです。 同じ接続でこのステートメントの後に実行された別のステートメントからも、 他の接続やクライアントが発行したステートメントからも影響を受けません。

注意: 数値が int の最大値をこえる場合、 文字列として返します。

例

例1 mysqli_stmt::$insert_id の例

オブジェクト指向型

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");

$stmt = $mysqli->prepare("INSERT INTO myCity (Name, CountryCode, District, Population) VALUES (?, ?, ?, ?)");

$name = 'Stuttgart';
$countryCode = 'DEU';
$district = 'Stuttgart';
$population = 617000;
$stmt->bind_param('sssi', $name, $countryCode, $district, $population);
$stmt->execute();

printf("New record has ID %d.\n", $stmt->insert_id);

手続き型

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");

$stmt = mysqli_prepare($link, "INSERT INTO myCity (Name, CountryCode, District, Population) VALUES (?, ?, ?, ?)");

$name = 'Stuttgart';
$countryCode = 'DEU';
$district = 'Stuttgart';
$population = 617000;
mysqli_stmt_bind_param($stmt, 'sssi', $name, $countryCode, $district, $population);
mysqli_stmt_execute($stmt);

printf("New record has ID %d.\n", mysqli_stmt_insert_id($stmt));

上の例の出力は以下となります。

New record has ID 1.

参考

  • mysqli_insert_id
  • mysqli_stmt_affected_rows
  • mysqli_stmt_execute