How To Get The Last MySQL Auto-ID in PHP

Posted on March 6, 2008 by admin.
Categories: PHP Programming.

There will be times when you will need to retrieve the last auto id on a table where you just did an insert. They way to do this is as follows:

<?php

$link = mysql_connect(’host’, ‘user’, ‘pass’);

if(!$link)
{
die(’could not connect: ‘. mysql_error() ) ;
}

mysql_query(”INSERT INTO table (field) values (’val1′)” );

echo “Last ID is “.mysql_insert_id());

Be sure you do this directly after the insert, if you need to use it for something, because it changes anytime another insert is done on a table with an auto id.

I have also noticed weird results on the first entry of a blank table, so watch out for that.

del.icio.us Slashdot Digg Facebook Technorati StumbleUpon Yahoo Ask

1 comment.