MySQL Last Inserted ID
Monday, September 18, 2006 12:16:55 AM
The common way :
$query = "INSERT INTO table (id, value) VALUES ('', 'value')";
mysql_query($query) or die(mysql_error());
$id = mysql_result((mysql_query("SELECT * FROM table WHERE value = 'value'")), 0, 'id');
echo "The last inserted ID was :" . $id;
The easy way :
$query = "INSERT INTO table (id, value) VALUES ('', 'value')";
mysql_query($query) or die(mysql_error());
echo "The last inserted ID was :" . mysql_insert_id();
A useful snippet if you aren't familiar with the 'mysql_insert_id()' function. This will save you some coding and time if you've been using other common, longer ways in the past.















Skulled # Monday, September 25, 2006 9:20:43 PM
Run "SHOW TABLE STATUS [FROM dbname] [LIKE tblname]" query through a mysql_query(), and the resulting result resource has the insert id for the key with auto_increment set in the table under the value "Auto_increment"
It's a more eloborate version than the straightforward mysql_insert_id() function. But it works.
Antonie PotgieterContrid # Monday, September 25, 2006 9:35:57 PM
I think that when you are going to focus on optimization and speed, your method will most likely be a bit faster than having PHP do the work for you.
Thanks for the comment.
Brian Armsrongkillermonk # Wednesday, June 20, 2007 6:06:16 PM