PHP mysql_insert_id() Function

Definition and Usage

The mysql_insert_id() function returns the ID generated by the previous INSERT operation.

If the previous query does not generate an AUTO_INCREMENT ID, mysql_insert_id() returns 0.

Syntax

mysql_insert_id(connection)
Parameters Description
connection Optional. Specifies the MySQL connection. If not specified, then the last connection is used.

Description

mysql_insert_id() returns the given connection is the AUTO_INCREMENT ID number generated by the previous INSERT query. If not specified connection if not specified, then use the last opened connection.

Tips and Comments

Note:If you need to save this value for later use, make sure to call mysql_insert_id() immediately after the query that generates the value.

Example

<?php
$con = mysql_connect("localhost", "hello", "321");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
$db_selected = mysql_select_db("test_db",$con);
$sql = "INSERT INTO person VALUES ('Carter','Thomas','Beijing')";
$result = mysql_query($sql,$con);
echo "ID of the last inserted record is: " . mysql_insert_id();;
mysql_close($con);
?>

Output similar to:

ID of the last inserted record is: 5