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

ghz 1years ago ⋅ 7823 views

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?


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 usemysql_* functions in new code](https://stackoverflow.com/questions/12859942/why-shouldnt-i-use- mysql-functions-in-php). 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.