MySQLi Tutorial MySQLi References

mysqli $insert_id Property



The mysqli::$insert_id / mysqli_insert_id() function 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 also modifies 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.

Syntax

//Object-oriented style
$mysqli->insert_id;

//Procedural style
mysqli_insert_id(mysql)

Parameters

mysql Required. For procedural style only: Specify a mysqli object returned by mysqli_connect() or mysqli_init().

Return Value

Returns 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.

Example: Object-oriented style

The example below shows the usage of mysqli::insert_id property. Please note that the database must contain an AUTO_INCREMENT field.

<?php
//establishing connection to the database
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
  echo "Failed to connect to MySQL: ". $mysqli->connect_error;
  exit();
}

$query = "INSERT INTO Employee (Name, City, Salary) VALUES ('John', 'London', 2800)";
$mysqli->query($query);

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

//closing the connection
$mysqli->close();
?>

The output of the above code will be similar to:

New record has ID 1.

Example: Procedural style

The example below shows the usage of mysqli_insert_id() function. Please note that the database must contain an AUTO_INCREMENT field.

<?php
//establishing connection to the database
$mysqli = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: ". mysqli_connect_error();
  exit();
}

$query = "INSERT INTO Employee (Name, City, Salary) VALUES ('John', 'London', 2800)";
mysqli_query($mysqli, $query);

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

//closing the connection
mysqli_close($mysqli);
?>

The output of the above code will be similar to:

New record has ID 1.

❮ MySQLi Functions Reference