Home > Backend Development > PHP Tutorial > How to Retrieve the Last Inserted ID Using PDO in PHP?

How to Retrieve the Last Inserted ID Using PDO in PHP?

Susan Sarandon
Release: 2024-12-27 18:59:14
Original
250 people have browsed it

How to Retrieve the Last Inserted ID Using PDO in PHP?

PDO: Retrieving the Last Inserted ID

In database operations, it's often necessary to retrieve the ID of the last record inserted into a table. PDO (PHP Data Objects) offers the ability to do this through the PDO::lastInsertId() method.

To obtain the last inserted ID, you need to execute an SQL INSERT statement and use the PDO::lastInsertId() method on the PDO object. For example:

$stmt = $db->prepare("INSERT INTO `cell-place` (name) VALUES (?)");
$stmt->execute([$name]);
$id = $db->lastInsertId();
Copy after login

In this example, $db is the PDO object, $stmt is the prepared statement, and $name is the value to be inserted. The PDO::lastInsertId() method returns the auto-incremented ID of the newly inserted record.

If you attempt to use the LAST_INSERT_ID() function directly, as in your given code, you will encounter an error. This is because LAST_INSERT_ID() is an SQL function, not a PHP function. To use it with PDO, you must utilize the PDO::lastInsertId() method.

Alternatively, you can retrieve the last inserted ID using a direct SQL query:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$row = $stmt->fetch(PDO::FETCH_NUM);
$lastId = $row[0];
Copy after login

This approach executes a raw SQL query to retrieve the last inserted ID. It's less efficient than using PDO::lastInsertId(), but it's useful if you have complex SQL queries that require you to manually perform ID retrieval.

The above is the detailed content of How to Retrieve the Last Inserted ID Using PDO in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template