PDO::lastInsertId

(no version information, might be only in CVS)

PDO::lastInsertId --  Returns the ID of the last inserted row or sequence value

Description

string PDO::lastInsertId ( [string name] )

Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver.

注: This method may not return a meaningful/consistent result across different PDO drivers, because the underlying database may not even support the notion of auto-increment fields or sequences.

参数

name

Name of the sequence object from which the ID should be returned.

返回值

If a sequence name was not specified for the name parameter, PDOStatement::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, PDOStatement::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.


add a note add a note User Contributed Notes
dave at dtracorp dot com
18-Aug-2006 08:34
in case anyone was wondering
something like

$val = 5;
$sql = "REPLACE table (column) VALUES (:val)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':val', $val, PDO::PARAM_INT);
$stmt->execute();
$lastId = $dbh->lastInsertId();

will return the last inserted id, whether the record was replaced or simply inserted

the REPLACE syntax, simply inserts, or deletes > inserts
so lastInsertId() still works

refer to http://mysql.com/doc/refman/5.0/en/replace.html
for REPLACE usage
opik at opik dot ru
20-Dec-2005 10:10
Simple example:
<?php
try
{
  
$dbh = new PDO('mysql:host=localhost;dbname=test', 'root', 'passowd');

  
$smf = $dbh->prepare("INSERT INTO test (`numer`) VALUES (?)");
 
  
$a = mt_rand(1, 100);
  
$smf->bindParam(1, $a, PDO::PARAM_INT);
  
$smf->execute();
   print
$dbh->lastInsertId().'<br />';

  
$a = mt_rand(1, 100);
  
$smf->bindParam(1, $a, PDO::PARAM_INT);
  
$smf->execute();
   print
$dbh->lastInsertId();

  
$dbh = null;
}
catch (PDOException $e) {
   print
"Error!: " . $e->getMessage() . "<br/>";
   die();
}
?>