Web20 University

How to Get the Last Insert ID in PHP and MySQL

Last edited on
Get up to 65% Off Hosting with FREE SSL & FREE Domains!

* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.

When working with MySQL databases in PHP, one common task is inserting a new row into a table and then retrieving the unique ID of the newly inserted row. This ID is often an auto-incremented primary key, which can be very useful for subsequent operations like inserting related records in other tables, logging, or returning data to the user.

In this blog post, we will discuss how to get the last insert ID in PHP and MySQL, why it is important, and how to use the retrieved ID in practical examples.

Table of Contents

  1. What is the Last Insert ID?
  2. Why is the Last Insert ID Important?
  3. How to Retrieve the Last Insert ID in PHP and MySQL
  4. Practical Examples of Using the Last Insert ID
  5. Conclusion

1. What is the Last Insert ID?

In a typical MySQL table, rows are often uniquely identified by a primary key, usually an auto-incremented ID. Every time you insert a new row into the table, MySQL automatically generates a unique ID for that row, which increments from the previous value. The last insert ID refers to the most recent auto-incremented ID generated by MySQL during an INSERT operation.

For example, if you have a users table with an auto-increment user_id column, inserting a new user into the table will create a new unique user_id. You can retrieve this newly created user_id as the last insert ID.


2. Why is the Last Insert ID Important?

The last insert ID is crucial in various situations, including:

  • Inserting Related Data: When you insert a record into one table and need to use that record’s ID in another table. For example, inserting a new user and then adding their profile information in a separate profiles table, where you need to reference the user_id.
  • Returning Data to the User: If you’re creating a record and need to return the generated ID to the frontend (e.g., an API returning the newly created order_id to the user after placing an order).
  • Logging and Auditing: In scenarios where you want to track or log information about newly inserted rows by their IDs.

The last insert ID helps ensure that each new record is correctly tracked and referenced.


3. How to Retrieve the Last Insert ID in PHP and MySQL

PHP provides a simple and efficient way to retrieve the last insert ID after an INSERT query, using the mysqli_insert_id() function (for mysqli extension) or the lastInsertId() method (for PDO).

Using mysqli

The mysqli extension in PHP provides the mysqli_insert_id() function to retrieve the last insert ID. Here’s how you can use it:

<?php
// Step 1: Establish the connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);

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

// Step 2: Insert a new record
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', '[email protected]')";
if ($conn->query($sql) === TRUE) {
    // Step 3: 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;
}

// Step 4: Close the connection
$conn->close();
?>

Using PDO

If you are using PDO to interact with your MySQL database, you can retrieve the last insert ID using the lastInsertId() method:

<?php
// Step 1: Establish the PDO connection
$dsn = 'mysql:host=localhost;dbname=your_database';
$username = 'root';
$password = '';

try {
    $pdo = new PDO($dsn, $username, $password);

    // Step 2: Insert a new record
    $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
    $stmt->execute(['name' => 'John Doe', 'email' => '[email protected]']);

    // Step 3: Get the last inserted ID
    $last_id = $pdo->lastInsertId();
    echo "New record created successfully. Last inserted ID is: " . $last_id;
    
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

In both examples, the INSERT statement adds a new user to the users table, and the last_insert_id function retrieves the ID of the newly inserted user.


4. Practical Examples of Using the Last Insert ID

Once you’ve retrieved the last insert ID, you can use it in various scenarios. Below are some practical examples.

Suppose you have a users table and a profiles table where you want to store additional profile information for each user. After inserting a new user into the users table, you can insert the related profile data into the profiles table by using the last insert ID as a foreign key.

<?php
// Insert new user
$sql = "INSERT INTO users (name, email) VALUES ('Jane Doe', '[email protected]')";
$conn->query($sql);
$last_id = $conn->insert_id;

// Insert profile information for the newly inserted user
$sql_profile = "INSERT INTO profiles (user_id, bio, website) VALUES ($last_id, 'Web Developer', 'http://example.com')";
if ($conn->query($sql_profile) === TRUE) {
    echo "Profile created successfully for user ID: " . $last_id;
} else {
    echo "Error: " . $sql_profile . "<br>" . $conn->error;
}
?>

In this example, after inserting a user, the last insert ID (user_id) is used to insert related profile information in the profiles table.

Example 2: Returning the Insert ID in an API Response

In a REST API, you might want to return the ID of the newly created resource. Here’s an example of how you might return the order_id of a newly placed order:

<?php
// Insert a new order
$sql = "INSERT INTO orders (user_id, product_id, quantity) VALUES (1, 101, 2)";
$conn->query($sql);
$last_order_id = $conn->insert_id;

// Return the last insert ID in a JSON response
$response = [
    'status' => 'success',
    'order_id' => $last_order_id
];
echo json_encode($response);
?>

In this example, after creating a new order, the order_id is returned as part of the API response, which can be used by the frontend or another service.

Example 3: Logging the Insert ID for Auditing Purposes

When inserting a new record, you might want to log the last insert ID for audit trails or debugging purposes.

<?php
// Insert new user
$sql = "INSERT INTO users (name, email) VALUES ('John Smith', '[email protected]')";
$conn->query($sql);
$last_id = $conn->insert_id;

// Log the last inserted ID
$log_message = "User with ID " . $last_id . " was inserted on " . date('Y-m-d H:i:s');
file_put_contents('user_log.txt', $log_message . PHP_EOL, FILE_APPEND);
?>

This example shows how you can log the ID of a newly inserted user along with a timestamp.


5. Conclusion

Retrieving the last insert ID in PHP and MySQL is a crucial task when working with auto-incremented primary keys. Whether you’re inserting related data in another table, returning the ID in an API, or logging it for auditing, PHP provides straightforward ways to get this value using mysqli_insert_id() or lastInsertId() with PDO.

By effectively using the last insert ID, you can streamline your database operations and maintain proper relationships between data in different tables.

To dive deeper into PHP and MySQL database functions, you can refer to the official PHP documentation and MySQL documentation.


Get up to 65% Off Hosting with FREE SSL & FREE Domains!