PHP Tutorial - PHP mysqli_insert_id() Function






Definition

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

Syntax

Object oriented style

mixed $mysqli->insert_id;

Procedural style

mixed mysqli_insert_id ( mysqli $link )

Parameter

ParameterIs Required Description
connectionRequired.MySQL connection to use

Return

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.





Example

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*/
$con=mysqli_connect("localhost","my_user","my_password","my_db");

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

mysqli_close($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());
    exit();
}

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

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

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

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

$mysqli->close();
?>