How to Get the Last Auto-Incremented Number From MySQL

When you need to insert data into more than one table at a time in a normalized database with relationships between the tables, you will often need to obtain the record number of the data inserted into the first table before creating your query to insert data into the second table. This can be accomplished with a short series of commands. Use the following code immediately after you make the first query:

/* This query figures out what the last auto-
   incremented number was so that it can be 
   used in the next query or other action.
   This assumes you are using the $link variable
   used in most MySQL examples to store the
   information necessary to connect to your
   database.  */

$result = mysql_query($query, $link);
$row = mysql_fetch_array($result);
// following is the newly created record
$last_id = 0 + $row[0];