πŸŽ‰ New: Top 75 PHP Interview Questions for 2026 β€” Free for all learners
Beginner ⏱ min read πŸ”„ Updated
Home β€Ί

Advertisement

PHP MySQL Get Last Inserted ID – Complete Beginner Tutorial

When working with MySQL databases, many tables use an AUTO_INCREMENT primary key. After inserting a new record, you often need to know which ID was generated. This is useful for:

  • Creating user profiles
  • Linking related tables
  • Redirecting users
  • Logging activities

This tutorial explains how to get the last inserted ID in PHP MySQL using different methods, with examples and output.


What Is Last Inserted ID in PHP MySQL?

The last inserted ID is the AUTO_INCREMENT value generated by MySQL when a new row is inserted into a table.

Example:

INSERT INTO users (name, email) VALUES ('Rahul', 'rahul@example.com');

If the ID column is auto-incremented, MySQL automatically assigns a new ID. PHP can retrieve this value.


When Do You Need the Last Inserted ID?

You need the last inserted ID when:

  • Inserting user data and creating a profile page
  • Saving order details and order items
  • Inserting parent-child table records
  • Tracking newly created database entries

Prerequisites for Getting Last Inserted ID

Before proceeding, ensure you have:

  • PHP installed
  • MySQL database with AUTO_INCREMENT column
  • A working MySQLi database connection
  • Basic understanding of INSERT queries

Sample MySQL Table Used in Examples

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100)
);

PHP MySQL Database Connection Code

<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");

if (!$conn) {
    die("Database connection failed");
}
?>

Get Last Inserted ID Using mysqli_insert_id()

The mysqli_insert_id() function is the most common way to retrieve the last inserted ID.

<?php
$query = "INSERT INTO users (name, email)
          VALUES ('Amit', 'amit@gmail.com')";

if (mysqli_query($conn, $query)) {
    $last_id = mysqli_insert_id($conn);
    echo "Last Inserted ID: " . $last_id;
}
?>

Output:

Last Inserted ID: 5

Get Last Inserted ID After Insert with Variables

<?php
$name = "Neha";
$email = "neha@gmail.com";

$query = "INSERT INTO users (name, email)
          VALUES ('$name', '$email')";

mysqli_query($conn, $query);
echo "Inserted ID: " . mysqli_insert_id($conn);
?>

Output:

Inserted ID: 6

Get Last Inserted ID Using Prepared Statements

When using prepared statements, the method remains the same.

<?php
$stmt = mysqli_prepare($conn,
        "INSERT INTO users (name, email) VALUES (?, ?)");

mysqli_stmt_bind_param($stmt, "ss", $name, $email);

$name = "Ravi";
$email = "ravi@gmail.com";

mysqli_stmt_execute($stmt);

echo "Last Inserted ID: " . mysqli_insert_id($conn);
?>

Output:

Last Inserted ID: 7

Get Last Inserted ID and Use It in Another Query

This is common when inserting related data.

<?php
mysqli_query($conn,
    "INSERT INTO users (name, email)
     VALUES ('Pooja', 'pooja@gmail.com')");

$user_id = mysqli_insert_id($conn);

mysqli_query($conn,
    "INSERT INTO profiles (user_id, bio)
     VALUES ($user_id, 'Web Developer')");

echo "User and profile created successfully";
?>

Output:

User and profile created successfully

Important Rules for Getting Last Inserted ID

  • Works only for AUTO_INCREMENT columns
  • Returns ID generated by the last INSERT query
  • Must be called on the same database connection
  • Not affected by SELECT queries

PHP MySQL last inserted id, mysqli_insert_id, PHP get auto increment id, PHP MySQL insert id example, PHP MySQLi last insert id tutorial, PHP database tutorial


Common Mistakes When Getting Last Inserted ID

  • Calling mysqli_insert_id() before INSERT
  • Using a different database connection
  • Forgetting AUTO_INCREMENT column
  • Expecting ID after UPDATE query

Best Practices for Using Last Inserted ID in PHP

  • Always check INSERT success before fetching ID
  • Use transactions when inserting multiple related records
  • Keep the same database connection
  • Use prepared statements for security


Frequently Asked Questions (FAQ)

1. What function gets the last inserted ID in PHP MySQL?

mysqli_insert_id().

2. Does it work with prepared statements?

Yes, it works the same way.

3. Can I get last ID after UPDATE?

No, only after INSERT.

4. Does SELECT affect last inserted ID?

No, SELECT queries do not affect it.

5. Is last inserted ID session-specific?

Yes, it is connection-specific.

# Summary

Here is what you've learned in this lesson:

  • What Is Last Inserted ID in PHP MySQL?
  • When Do You Need the Last Inserted ID?
  • Prerequisites for Getting Last Inserted ID
  • Sample MySQL Table Used in Examples
  • PHP MySQL Database Connection Code
  • Get Last Inserted ID Using mysqli_insert_id()
  • Get Last Inserted ID After Insert with Variables
  • Get Last Inserted ID Using Prepared Statements
  • Get Last Inserted ID and Use It in Another Query
  • Important Rules for Getting Last Inserted ID
  • Common Mistakes When Getting Last Inserted ID
  • Best Practices for Using Last Inserted ID in PHP
  • Related tutorial:
  • Frequently Asked Questions (FAQ)
πŸš€
Next up: PHP MySQL Insert Data

Continue to the next lesson and learn more about PHP MySQL Insert Data.

Start Next Lesson β†’

← Previous Post
PHP MySQL Insert Data
Next Post β†’
PHP MySQL Insert Multiple Records