PHP MySQL Get Last Inserted ID
PHP MySQL Get Last Inserted ID
When inserting data into a MySQL 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_idis 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
-
Use
mysqli_insert_id()(procedural),$conn->insert_id(OO), or$conn->lastInsertId()(PDO). -
The last inserted ID is per connection, so it won’t interfere with other users inserting records simultaneously.
-
Useful for relational data, e.g., inserting into one table and using the ID in another table.
