Get Last Insert ID in PHP with MySQL PDO and MySQLi

Keeping track of the last record inserted is often important. Whether you are managing user registrations, processing orders, or handling other types of data, knowing the last ID inserted allows you to link related records, retrieve specific data, or perform additional actions.

In this article, you will learn how to retrieve the last inserted ID in your database operations, and the common methods used to implement this functionality. You will also see examples and tips for ensuring accuracy when working with last insert IDs.

What is LAST_INSERT_ID()?

LAST_INSERT_ID() is a MySQL function that returns the last automatically generated value for the AUTO_INCREMENT column during an INSERT operation. This value is specific to the current connection, ensuring that it reflects only the most recent insert in your session.

SELECT LAST_INSERT_ID();

Here is an example:

INSERT INTO orders (product_id, quantity) VALUES (101, 5); SELECT LAST_INSERT_ID();

If you do not use LAST_INSERT_ID(), it can be hard to get the right value, especially when adding multiple records.

Let’s see how to use that with PHP.

Get the Last Inserted ID with mysqli_insert_id

The mysqli_insert_id function is one of the common ways to retrieve the ID of the last row inserted into a table. This function is really handy when your table has an auto-increment column, as it lets you get the generated ID right after running an INSERT query.

This is the syntax you will use:

$last_id = mysqli_insert_id($connection);

Here is an example:

// Set up a connection to your MySQL database.
$connection = new mysqli('localhost', 'username', 'password', 'database');

// Make sure the connection works.
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// Add a new record to the table
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'johndoe@example.com')";

if ($connection->query($sql) === TRUE) {
    // Get the ID of the latest entry
    $last_id = mysqli_insert_id($connection);
    echo "The last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $sql . "<br>" . $connection->error;
}

// This line will end the connection
$connection->close();

In the section below, I will show you how to get the ID using the lastInsertId method in PDO.

Using PDO lastInsertId Method

If you are working with PHP PDO (PHP Data Objects) for database interactions, the lastInsertId method is your best solution for retrieving the ID of the recently inserted row. This method is simple to use and provides a way to handle auto-incremented IDs in your database.

Here is its syntax:

$lastId = $pdo->lastInsertId();

Here is an example:

try {
    // Create a PDO connection
    $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Insert a new record into a table
    $sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':name' => 'Jane Doe',
        ':email' => 'janedoe@example.com'
    ]);

    // Retrieve the last inserted ID
    $lastId = $pdo->lastInsertId();
    echo "The last inserted ID is: " . $lastId;

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

Did you think about what happens if no record is inserted? Let’s see how to handle errors when getting the last inserted ID from the database with PHP.

Handling Errors When Getting the Last Inserted ID in PHP

You can handle errors as shown in the following example when using the mysqli extension:

$connection = new mysqli('localhost', 'username', 'password', 'database');

// Check the connection
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// Execute the INSERT query
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'johndoe@example.com')";
if ($connection->query($sql) === TRUE) {
    // Attempt to retrieve the last inserted ID
    $last_id = mysqli_insert_id($connection);
    if ($last_id) {
        echo "The last inserted ID is: " . $last_id;
    } else {
        echo "Error: Unable to retrieve the last inserted ID.";
    }
} else {
    // Handle query failure
    echo "Error: " . $connection->error;
}

// Close the connection
$connection->close();

Here is how you can handle errors when using PDO:

try {
    // Create a PDO connection
    $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Execute the INSERT query
    $sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':name' => 'Jane Doe',
        ':email' => 'janedoe@example.com'
    ]);

    // Attempt to retrieve the last inserted ID
    $lastId = $pdo->lastInsertId();
    if ($lastId) {
        echo "The last inserted ID is: " . $lastId;
    } else {
        echo "Error: Unable to retrieve the last inserted ID.";
    }
} catch (PDOException $e) {
    // Handle any exceptions
    echo "Error: " . $e->getMessage();
}

Let’s summarize it.

Wrapping Up

We went over how to grab the last inserted ID with some examples to help you get started. We also talked about handling errors so your app works smoothly, even when things go wrong.

Let’s quickly go over what we covered

  • LAST_INSERT_ID(): This gets the last auto-generated ID in your current session.
  • mysqli_insert_id: You can use this to get the last ID when you are working with MySQL in PHP.
  • PDO lastInsertId: A method to get the last inserted ID when using PDO for database interactions.
  • Error Handling: Make sure your queries run successfully and handle errors when grabbing the last ID.

Similar Reads

PHP Magic Constants: Simplify Your Code

There are some tools known as "PHP magic constants" that will make your code a little more clever and versatile.…

Class and Object in PHP: How They Work with a Real Example

Classes and objects are important parts of OOP in PHP. They help you organize your code so you can update…

PHP str_replace Function: How it Works with Examples

If you find a word that does not fit and want to fix it. You can use the PHP str_replace…

PHP Namespace: How to Group Code (With Example)

PHP namespace solves the problem of name conflicts. Different developers may create functions-classes, or constants with the same name. PHP…

PHP sizeof: How to Count Elements in Arrays with Examples

The sizeof function in PHP exists to help developers know how many items an array holds. Understand the sizeof Function…

PHP strict_types: How the Strict Mode Works

If you want to write good PHP code, strict mode should be on your radar. Strict mode—activated by the command declare(strict_types=1); at…

PHP For Loop: Run Code Using a Counter with Examples

You may need to repeat tasks in PHP. The PHP for loop solves this by letting you run code many…

PHP fread Function: How to Read Files in PHP

In some cases, you need to handle a lot of data or simply try to open a file, or read…

How to Connect a MySQL Database to PHP?

Connecting PHP to MySQL is not just a technical step—it is the basic part of how data-driven websites work. From…

PHP array_pop: Remove and Return the Last Element of an Array

The array_pop function in PHP gives you a direct way to take the last element from an array. Understand the…

Previous Article

How to Insert Multiple Rows in MySQL with PHP?

Next Article

How to Select Data Using PHP and MySQL?

Write a Comment

Leave a Comment

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


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.