How do I get the last inserted ID of a MySQL table in PHP?

How do I get the last inserted ID of a MySQL table in PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How do I get the last inserted ID of a MySQL table in PHP?

When dealing with auto-incrementing primary keys, the instinctive reaction is often to run SELECT MAX(id) FROM table_name. While this query will return the highest value currently present in the id column, it is fundamentally inefficient for high-volume applications. Scanning an entire index to find the maximum value is an O(N) operation relative to the number of rows examined, whereas retrieving the last inserted ID is a constant-time operation supported directly by the database engine.

The correct approach depends entirely on whether you need the ID immediately after an insertion or if you are looking at historical data where no new inserts have occurred recently. If your goal is to retrieve the identifier of the row just created, relying on MAX(id) is technically incorrect because it ignores the performance implications and assumes the table does not have gaps in its auto-increment sequence due to deleted rows.

Using the LAST_INSERT_ID() Function

The standard method for retrieving the last inserted ID is using the MySQL-specific function LAST_INSERT_ID(). This function is atomic to the connection; it returns the value generated by the most recent INSERT statement on that specific session, regardless of what other connections are doing.

In raw PHP using PDO or mysqli, you can retrieve this value immediately after executing your insert:

// Example using PDO
$stmt = $pdo->prepare('INSERT INTO users (name) VALUES (?)');
$stmt->execute(['Alice']);

$lastId = $pdo->lastInsertId();
echo $lastId; // Returns the numeric ID of the newly inserted row

In MySQLi, the equivalent is $conn->insert_id. This mechanism ensures thread safety regarding the specific connection. If you have multiple connections to your database (which is common in load-balanced architectures), each application instance will see its own LAST_INSERT_ID() value. It does not return the globally highest ID across all tables or connections, only the one generated on that specific socket.

Why Not MAX(id)?

You asked if this is similar to SELECT MAX(id) FROM table. The answer is no, and here is why it matters for production systems.

When you run a query like SELECT MAX(id) FROM users, the database engine must scan the primary key index to find the highest value. In a table with millions of rows, this adds unnecessary I/O overhead every time you need an ID. Furthermore, if your application deletes rows, MAX(id) will return the ID of a row that no longer exists. For example, if ID 5 is deleted from a table containing IDs 1 through 10, MAX(id) returns 10. However, if you just inserted a new row and want to know its ID, LAST_INSERT_ID() gives you the exact value returned by the insert operation, even if it skips numbers due to previous deletions.

Handling Concurrent Connections

A common pitfall arises when multiple PHP scripts or background workers interact with the same database. If Worker A inserts a row and tries to read the last ID using MAX(id), but Worker B has already inserted a larger value in the meantime, you might get confused if you are comparing values across different sessions.

LAST_INSERT_ID() solves this by being session-local. It ensures that even if another process inserts a record with ID 9001, your current connection still reports the ID generated by your own specific INSERT statement. This is crucial for generating unique URLs or referencing new records in foreign keys immediately after creation.

When You Don't Need the Last Inserted ID

There are scenarios where fetching the last inserted ID is unnecessary. If you are using UUIDs or random strings as primary keys, LAST_INSERT_ID() will return 0 or null because no auto-increment integer was generated. In such cases, you must handle the ID generation outside the database or ensure your application logic accounts for non-integer identifiers.

If you are using a framework like Laravel, the ORM abstracts this away entirely by returning the model instance with its assigned key, making manual calls to lastInsertId() redundant unless you are writing raw queries for specific optimization needs. For most standard use cases involving auto-increment integers, leveraging the database connection's built-in tracking is the most robust and performant solution available.

Our network