Get the last inserted ID of a MySQL table in PHP

Get the last inserted ID of a MySQL table is a simple query to obtain the primary key of the record you just inserted to the table. Here I have explained the query using PDO as well as Mysqli.

Also, I have abbreviated few points while using PDO or if you are trying to get the last inserted ID of a MySQL table in PHP using other methods.

Get the last inserted ID using PDO

It will be better to mention some facts here to clarify few misconception regarding PDO:

  1. You will never get the wrong ID if you use mysql_insert_id right after your mysql_query even if you have a lot of inserts happening (eg your database also logs something).
    If of course you execute several other queries on the same connection in between, you may face the issue.
  2. You don’t need to worry about other processes doing inserts. No need to wrap the query in a transaction. The mysql manual says: “The ID that was generated is maintained in the server on a per-connection basis“.
    This means that the value returned by the function to a given user is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that user.
Get the last inserted ID using Mysqli

In above code I have used Procedural style. You can use Object oriented style but read this article as few users have reported bug in this approach.


 If you’re using Mysql then stop using mysql_* functions in new code. They are no longer maintained and are officially deprecated.

And at last if you are using SELECT MAX(id) FROM table to get the last inserted ID of a MySQL table then the main problem of this method is concurrency means you can get wrong id if another user inserted a record in between.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.