PHP Get ID of Last Inserted Record

In the PHP MySQL insert chapter you've learnt MySQL automatically generate an unique ID for the AUTO_INCREMENT column each time you insert a new record or row into the table. However, there are certain situations when you need that automatically generated ID to insert it into a second table. In these situations you can use the PHP mysqli_insert_id() function to retrieve the most recently generated ID, as shown in the upcoming example.

If we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get the ID of the last inserted/updated record immediately.

Example -

In database design, you often use a surrogate key to generate unique integer values for the primary key column using the AUTO_INCREMENT attribute. It means when you insert a new row into the table that has an AUTO_INCREMENT column, MySQL automatically generates a unique integer and use it for the column. For more information on how to set the AUTO_INCREMENT attribute for a column, check it out the MySQL sequence tutorial. You can obtain the generated sequence number using the MySQL LAST_INSERT_ID function and use the number for the next statements e.g., inserting a new row into a correlated table.

Example -

The following examples are equal to the examples from the previous page (PHP Insert Data Into MySQL), except that we have added one single line of code to retrieve the ID of the last inserted record. We also echo the last inserted ID:

The LAST_INSERT_ID function works based on client-independent principle. It means the value returned by the LAST_INSERT_ID function for a specific client is the value generated by that client only. This ensures that each client can obtain its own unique ID.

Example -

Example -