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_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.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *