Discover Auto Increment ID After MySQL Insert With PHP

9th March 2008 - 1 minute read time

Inserting a value into a database with an auto incrementing field is quite common. Once you insert the new row you would expect that you need to do another query to get the newly created ID.

Another option is to use the mysql_insert_id() function to retrieve the ID created by the last insert statement.

// insert
$sql = 'INSERT INTO table(colum1, colum2) VALUES(1, 2);';
mysql_query($sql);
 
// get new id
$id = mysql_insert_id();

The $id variable will now contain your most recently inserted ID.

Comments

Permalink
with this code we can find next record id (that is mean if multi user working by db, this number is not what thing that we want)

esmailzadeh (Mon, 05/03/2010 - 13:37)

Add new comment

The content of this field is kept private and will not be shown publicly.