mysqli::$insert_id
mysqli_insert_id
Returns the value generated for an AUTO_INCREMENT column by the last query
Description
Object-oriented style
intstring$mysqli->insert_id;
Procedural style
intstring mysqli_insert_id(mysqli $mysql
)
Performing an INSERT
or UPDATE
statement using the LAST_INSERT_ID()
MySQL function will also modify the value returned by mysqli_insert_id.
If LAST_INSERT_ID(expr)
was used to generate the value of
AUTO_INCREMENT
, it returns the value of the last expr
instead of the generated AUTO_INCREMENT
value.
Returns 0
if the previous statement did not change an
AUTO_INCREMENT
value. mysqli_insert_id must be
called immediately after the statement that generated the value.
Parameters
-
mysql
-
Procedural style only: A mysqli object
returned by mysqli_connect or mysqli_init
Return Values
The value of the AUTO_INCREMENT
field that was updated
by the previous query. Returns zero if there was no previous query on the
connection or if the query did not update an AUTO_INCREMENT
value.
Only statements issued using the current connection affect the return value. The
value is not affected by statements issued using other connections or clients.
Note:
If the number is greater than the maximum int value, it will be returned as
a string.
Examples
Example #1 $mysqli->insert_id example
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf("New record has ID %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
mysqli_query($link, "CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
mysqli_query($link, $query);
printf("New record has ID %d.\n", mysqli_insert_id($link));
/* drop table */
mysqli_query($link, "DROP TABLE myCity");
The above examples will output: