How do I get the last inserted ID of a MySQL table in PHP?


Question

I have a table into which new data is frequently inserted. I need to get the very last ID of the table. How can I do this?

Is it similar to SELECT MAX(id) FROM table?

1
87
1/30/2014 5:57:40 PM

Accepted Answer

If you're using PDO, use PDO::lastInsertId.

If you're using Mysqli, use mysqli::$insert_id.

If you're still using Mysql:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

But if you have to, use mysql_insert_id.

125
5/23/2017 12:26:06 PM

there is a function to know what was the last id inserted in the current connection

mysql_query('INSERT INTO FOO(a) VALUES(\'b\')');
$id = mysql_insert_id();

plus using max is a bad idea because it could lead to problems if your code is used at same time in two different sessions.

That function is called mysql_insert_id


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon