In this tutorial, we will learn how to get the Last Inserted ID in MySQL using PHP. If you perform an INSERT operation on a table with an AUTO_INCREMENT field, you can retrieve the ID of the last inserted record immediately using:
- the
insert_idproperty in MySQLi, or - the
lastInsertId()method in PDO.
This ID is usually an AUTO_INCREMENT primary key generated automatically by MySQL. Let us understand first what Last Inserted ID is in MySQL.
What is Last Inserted ID in MySQL?
The last inserted ID is the value automatically generated by MySQL when you insert a new record into a table with an AUTO_INCREMENT column. Let us write SQL query to create a table in MySQL.
// SQL query to create table.
$sql = "CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(150) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";If you insert data into this table using the following SQL query:
INSERT INTO students (name, email)
VALUES ('John', 'john@gmail.com');MySQL automatically generates:
id = 1
This value is called the last inserted ID.
How to Get Last Inserted ID in MySQL Using PHP?
PHP provides multiple ways to get the last inserted ID in MySQL:
- MySQLi method (Procedural and Object-Oriented)
- PDO method
Let us learn each method one by one with examples.
Requirements Before Getting Last Inserted ID
Before getting the last inserted ID, make sure the following requirements are met:
- MySQL database is created.
- PHP is connected to the MySQL database.
- The table exists in the database.
- The table must have an AUTO_INCREMENT column. This is because the last inserted ID works only with AUTO_INCREMENT fields. Usually, this is the primary key.
[blocksy-content-block id=”12371″]
Getting Last Inserted ID Using MySQLi
Inside the htdocs folder, create a new file with name last_inserted_id.php and paste this code into it.
Example 1: Using Object-Oriented MySQLi
<?php
// Include database connection.
require_once "connect.php";
$sql = "INSERT INTO students (name, email, age)
VALUES ('Saanvi', 'saanvi@gmail.com', 18)";
if ($conn->query($sql) === TRUE) {
// Get the last inserted id.
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close the connection.
$conn->close();
?>Now save this file using Ctrl + S.
Now open the browser and go to http://localhost/last_inserted_id.php. If a new record is inserted into the table, you will see the following output in your browser.
Output:
New record created successfully. Last inserted ID is: 35463
[blocksy-content-block id=”12121″]
Check Last Inserted ID into Database Using phpMyAdmin
To check the last inserted ID of a new record into a table using phpMyAdmin, follow all these steps:
- Open your browser and type the following URL in the address bar:
http://localhost/phpmyadmin. - Press Enter.
- The phpMyAdmin dashboard will open in your browser.
- In the left-side panel, you will see a list of databases.
- Click on your database name (Example: scientecheasy_db).
- After clicking the database name, you will see all the tables inside the database.
- Click on your table name. (Example: students)
- After clicking the table, you will see several tabs at the top:
- Click on the browser tab where you will see all inserted records in the table.
- MySQL automatically generates the ID if the column is set to AUTO_INCREMENT. The highest AUTO_INCREMENT value is always the last inserted ID.
- Now look at the id column. The last row usually shows the last inserted ID.
Explanation of PHP Code
- The line require_once “connect.php”; includes the database connection file.
- This file connect.php contains the code that connects PHP to the MySQL database.
- After this line require_once “connect.php”;, the variable $conn is available for use.
- Without this connection file, PHP cannot communicate with the database.
- Then, we created a SQL statement and stored it inside the variable $sql.
- The INSERT INTO statement inserts a new record into the students table and adds the following values:
- name = Saanvi
- email = saanvi@gmail.com
- age = 18
- This query adds one new student record to the table.
- The $conn->query() function in PHP sends the SQL query to the database and executes it. Here,
- $conn is the database connection.
- $sql contains the insert query.
- If the query runs successfully, it returns TRUE.
- If it fails, it returns FALSE.
- The line $conn->insert_id retrieves the ID of the last inserted record.
- This works only if the table contains an AUTO_INCREMENT column.
- MySQL automatically generates this ID.
- PHP stores and returns this value using $conn->insert_id.
- If the data is inserted without any errors, PHP will display a success message and the last inserted ID in the browser.
- If something goes wrong, PHP will show the error message.
- The line $conn->close(); closes the connection between PHP and the MySQL database. This frees up server resources.
- It is good practice to close the connection after completing the database task.
[blocksy-content-block id=”12153″]
Example 2: Using MySQLi Procedural
<?php
// Include database connection.
require_once "connect.php";
$sql = "INSERT INTO students (name, email, age)
VALUES ('John', 'john@example.com', 20)";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>Getting Last Inserted ID Using PDO
Example 3: Using PDO to Get Last Inserted ID
<?php
// Include database connection.
require_once "connect.php";
try {
$sql = "INSERT INTO students (name, email, age)
VALUES ('Smith', 'smith@example.com', 21)";
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
// Closing connection.
$conn = null;
?>In this example, the line $pdo->lastInsertId() retrieves the ID of the last inserted record into a database table. This method works when the table contains an AUTO_INCREMENT column, usually the primary key.
Conclusion
PHP provides multiple ways to retrieve the last inserted ID after inserting a record into a MySQL table with an AUTO_INCREMENT column:
- mysqli_insert_id() → Used in MySQLi Procedural style
- $conn->insert_id → Used in MySQLi Object-Oriented style
- $conn->lastInsertId() → Used in PDO (Recommended and more secure)
These methods allow you to obtain the unique ID generated automatically by MySQL for the last inserted record. We hope you have learned how to get the last inserted ID in MySQL using PHP and practiced all the examples provided in this tutorial.


