PHP MySQL Get Last Inserted ID

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

Related tutorial:


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.

Related Article
50+ PHP Interview Questions and Answers 2023

1. Differentiate between static and dynamic websites. Static Website The content cannot be modified after the script is executed The Read more

All We Need to Know About PHP Ecommerce Development

  Many e-commerce sites let you search for products, show them off, and sell them online. The flood of money Read more

PHP Custom Web Development: How It Can Be Used, What Its Pros and Cons Are,

PHP is a scripting language that runs on the server. It uses server resources to process outputs. It is a Read more

PHP Tutorial

PHP Tutorial – Complete Guide for Beginners to Advanced Welcome to the most comprehensive PHP tutorial available online at PHPOnline.in Read more

Introduction of PHP

Introduction to PHP – Learn PHP from Scratch with Practical Examples Welcome to your complete beginner's guide to PHP. Whether Read more

Syntax Overview of PHP

Syntax Overview of PHP (2025 Edition) Welcome to phponline.in, your one-stop platform for mastering PHP. This comprehensive, SEO-rich tutorial on Read more

Environment Setup in PHP

Setting Up PHP Environment (Beginner’s Guide) If you’re planning to learn PHP or start developing websites using PHP, the first Read more

Variable Types in PHP

PHP Variable Types: Complete Beginner's Guide to PHP Data Types Welcome to phponline.in, your trusted source for beginner-to-advanced level PHP Read more