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();
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];
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!