PHP MySQL Get Last Inserted ID

PHP Tutorial

PHP MySQL Get Last Inserted ID

In PHP MySQL Get Last Inserted ID in table with an AUTO_INCREMENT primary key, you may want to get the ID of the newly inserted record. PHP provides methods to retrieve it.


1️⃣ Using mysqli_insert_id() (Procedural)


 

mysqli_insert_id($conn) returns the last inserted auto-increment ID for the connection.


2️⃣ Using mysqli Object-Oriented


 

  • $conn->insert_id is the object-oriented way of retrieving the last ID.


3️⃣ Using PDO


 

$conn->lastInsertId() works with PDO to return the last auto-increment ID.


4️⃣ Key Points

  1. Use mysqli_insert_id() (procedural), $conn->insert_id (OO), or $conn->lastInsertId() (PDO).

  2. The last inserted ID is per connection, so it won’t interfere with other users inserting records simultaneously.

  3. Useful for relational data, e.g., inserting into one table and using the ID in another table.

You may also like...