It should be noted here at this function will not display the correct ID if issuing ON DUPLICATE KEY UPDATE.
Example on a new Row:
<?php
$sql = "INSERT INTO city (`city`) VALUES ('Paris') ON DUPLICATE KEY UPDATE `city` = 'Paris";
$dbh->query($sql);
echo $dbh->lastInsertId();
?>
Above displays: 1
Expected display: 1
Example on an existing row that gets updated:
<?php
$sql = "INSERT INTO city (`city`) VALUES ('Paris') ON DUPLICATE KEY UPDATE `city` = 'Paris";
$dbh->query($sql);
echo $dbh->lastInsertId();
?>
Above displays: 2
Expected display: 1 (since no new records were inserted)
You'll have to work around this.
PDO->lastInsertId()
(PHP 5 >= 5.1.0, PECL pdo:0.1-1.0.3)
PDO->lastInsertId() — Returns the ID of the last inserted row or sequence value
Description
Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver. For example, PDO_PGSQL() requires you to specify the name of a sequence object for the name parameter.
Note: This method may not return a meaningful or consistent result across different PDO drivers, because the underlying database may not even support the notion of auto-increment fields or sequences.
Parameters
- name
-
Name of the sequence object from which the ID should be returned.
Return Values
If a sequence name was not specified for the name parameter, PDO->lastInsertId() returns a string representing the row ID of the last row that was inserted into the database.
If a sequence name was specified for the name parameter, PDO->lastInsertId() returns a string representing the last value retrieved from the specified sequence object.
If the PDO driver does not support this capability, PDO->lastInsertId() triggers an IM001 SQLSTATE.
PDO->lastInsertId()
28-Apr-2008 07:17
