Sunday, March 29, 2009

PHP/Mysql: Get the last inserted auto increment field

Lets say you have inserted a row inside your mysql table from PHP, and now you need the ID value that just inserted as auto incremental field. Mysql has a function that returns the last inserted auto incremental field. The function is LAST_INSERT_ID()

You can easily call the function from your PHP code. I'm providing the PHP code for you that will retrieve the last auto incremented field from mysql.

## get the last inserted auto increment id from mysql table
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$id = $row['ID'];

That's it. This will need you when you have inserted a row at mysql, and the auto incremented field is a foreign key of another table. That case you just get the ID using above method, and use at that table.


Anonymous said...

Excellent!!! this is exactly what i was looking for!

Thank you for posting it!

Anilkumar kg said...

This is ok.....but in a multiuser environment (for 1000 concurrent users) how can u guarentee this

Anonymous said...

This function is set per session, so you would get the last inserted ID of wherever you exactly inserted from. It is guaranteed.

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...