Name

mysql_insert_id

Synopsis

int mysql_insert_id([cresource connection])

Returns the most recently generated AUTO_INCREMENT identifier value associated with a connection. An optional connection resource handle may be provided as the parameter; otherwise, the most recently opened connection that is still open is assumed.

This function works for a connection and not on a per-query basis. Subsequent INSERT statements through the same connection make it impossible to retrieve previous identifier values using this function. The return value is not affected by non-INSERT SQL statements.

The function returns false if there have been no AUTO_INCREMENT identifiers for the connection.

Example

<?php
  $query = "INSERT INTO presents 
            VALUES(NULL, \"Bike\", \"Fitzroy Cycles\", 1, \"Red\", \"350.00\", NULL)";
  
  $connection = mysql_connect("localhost", "root", "drum");
  mysql_select_db("wedding", $connection);
  
  $result = mysql_query($query, $connection);
  
  echo "Inserted record " . mysql_insert_id($connection);            
?>

Get Managing & Using MySQL, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.