Discover Auto Increment ID After MySQL Insert With PHP

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

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)
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.