PHP CHAPTER 34

MySQL Get Last ID

MySQLi insert_id returns the AUTO_INCREMENT ID generated by the latest insert on a connection.

📘

What is it?

MySQLi insert_id returns the AUTO_INCREMENT ID generated by the latest insert on a connection.

💡

Why do we use it?

Applications often need the new record ID to create related records.

⚙️

How does it work?

After a successful INSERT, the connection object exposes insert_id.

🧩

Syntax

PHP Syntax
$conn->insert_id;
💻

Example

PHP Example
<?php

$conn = new mysqli("localhost", "root", "", "aifa_php_lab");

$name = "Riya";
$email = "riya@example.com";

$stmt = $conn->prepare("INSERT INTO students (name,email) VALUES (?,?)");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();

echo "New Student ID: " . $conn->insert_id;

?>
🔍

Example Explained

After execute, insert_id contains the generated student ID.
🚀

More Examples

Use the new ID to insert related student-course data.

⚠️ Important Rules

Use the same database connection that performed the INSERT.

❌ Common Mistakes

Trying to read insert_id from another connection.

🌍 Real-World Use

Creating parent and child database records.

📝 Practice Exercise

Insert a student and display the generated ID.

💻 Try It Yourself

Write and run this PHP lesson inside the AIFA Coding Lab.

Open Coding Lab →