MySQL: Finding the ID of the Last Inserted Record
Many times you insert a new record into a database and you need to know the ID of that record, either to display the modified content or maybe to link the ID to another table. This is easy to do using the PHP built-in function mysql_insert_id().
Assumption is that the table you are inserting into will have an auto-incrementing field.
// Connect to the Database
$connection = mysql_connect($DBhost,$DBuser,$DBpassword);
$db = mysql_select_db($DBdatabase, $connection);
// Execute the update query
$sql="INSERT INTO myTable (Name,Phone,OrderRef) VALUES ('$Name','$Phone',$OrderNumber)";
// Check the result
$result = mysql_query($sql) or die("Query failed: SQL=[$sql] " . mysql_error());
// You can now get the ID of the last inserted record
$LastID = mysql_insert_id();