PHP Tutorial - PHP mysqli_insert_id() Function


The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) used in the last query.


Object oriented style

mixed $mysqli->insert_id;

Procedural style

mixed mysqli_insert_id ( mysqli $link )


ParameterIs Required Description
connectionRequired.MySQL connection to use


It returns an the value of AUTO_INCREMENT field updated by the last query.

It returns zero if there were no update or no AUTO_INCREMENT field.


The Employee table has an auto-generated id field. The following code gets the id used in the last query.

<?php/*  w  ww.  ja  v a  2  s . com*/

if (mysqli_connect_errno($con)){
  echo "Failed to connect to MySQL: " . mysqli_connect_error();

mysqli_query($con,"INSERT INTO Employee (name) VALUES('PHP')");

// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con); 


Example 2

<?php//ww  w .  ja  v  a2 s  .  co  m
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());

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

$query = "INSERT INTO myCity (name)VALUES ('New York')";

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

$mysqli->query("DROP TABLE myCity");