w3resource

PHP mysqli: insert_id() Function

mysqli_insert_id() function / mysqli::$insert_id

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

Name Description Required/Optional
link A link identifier returned by mysqli_connect() or mysqli_init() Required for procedural style only and Optional for Object oriented style

Usage: Procedural style

mysqli_insert_id(connection);

Parameter:

Name Description Required / Optional
connection Specifies the MySQL connection to use Required

Return value:

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.

Version: PHP 5, PHP 7

Example of object oriented style:


<?php
$mysqli = new mysqli("localhost", "user1", "datasoft123", "hr");

/* 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 VALUES (NULL, 'Mumbai', 'WB', 'Mumbai', 713005)";
$mysqli->query($query);

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

/* drop table */
$mysqli->query("DROP TABLE myCity");

/* close connection */
$mysqli->close();
?>

Example of procedural style:


<?php
$link = mysqli_connect("localhost", "use1r", "datasoft123", "hr");

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

mysqli_query($link, "CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Mumbai', 'WB', 'Mumbai', 713005)";
mysqli_query($link, $query);

printf ("New Record has id %d.\n", mysqli_insert_id($link));

/* drop table */
mysqli_query($link, "DROP TABLE myCity");

/* close connection */
mysqli_close($link);
?>

Output

New Record has id 1

Example:

<?php
$con=mysqli_connect("localhost","user1","datasoft123","hr");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

mysqli_query($con,"INSERT INTO employees (First_Name,Last_Name,Age) 
VALUES ('David','Skolnick',35)");
 
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con); 

mysqli_close($con);
?>

Sample Output:

New record has id: 0

See also

PHP Function Reference

Previous: init
Next: kill



Follow us on Facebook and Twitter for latest update.