Documentation Home
Connectors and APIs Manual
Download this Manual
PDF (US Ltr) - 5.3Mb
PDF (A4) - 5.3Mb


Connectors and APIs Manual  /  ...  /  mysqli::$insert_id, mysqli_insert_id

7.3.8.28 mysqli::$insert_id, mysqli_insert_id

Copyright 1997-2022 the PHP Documentation Group.

  • mysqli::$insert_id

    mysqli_insert_id

    Returns the value generated for an AUTO_INCREMENT column by the last query

Description

Object-oriented style

int|string mysqli->insert_id ;

Procedural style

int|string mysqli_insert_id(mysqli mysql);

Returns the ID generated by an INSERT or UPDATE query on a table with a column having the AUTO_INCREMENT attribute. In the case of a multiple-row INSERT statement, it returns the first automatically generated value that was successfully inserted.

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 7.61 $mysqli->insert_id example

Object-oriented style

<?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");

Procedural style

<?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:

New record has ID 1.