Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : PDO Functions : PDO->lastInsertId()

PDO->lastInsertId()

Returns the ID of the last inserted row or sequence value ()


Code Examples / Notes » pdo_lastinsertid

opik

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();
}
?>


dennis du krøger

It should be noted that, at least for MySQL using InnoDB tables, with transactions PDO will report the last insert id as 0 after the commit, the real ids are only reported before committing.
(As a side note, MySQL keeps the ID number incremented after a rollback).


yonatan ben-nes

It should be mentioned that this function DOES NOT retrieve the ID (Primary key) of the row but it's OID instead.
So if you use one of the latest PostgreSQL versions this function won't help you unless you add OID to the table specifically when you create it.


dave

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


Change Language


Follow Navioo On Twitter
PDO->beginTransaction()
PDO->commit()
PDO->__construct()
PDO->errorCode()
PDO->errorInfo()
PDO->exec()
PDO->getAttribute()
PDO->getAvailableDrivers()
PDO->lastInsertId()
PDO->prepare()
PDO->query()
PDO->quote()
PDO->rollBack()
PDO->setAttribute()
PDOStatement->bindColumn()
PDOStatement->bindParam()
PDOStatement->bindValue()
PDOStatement->closeCursor()
PDOStatement->columnCount()
PDOStatement->errorCode()
PDOStatement->errorInfo()
PDOStatement->execute()
PDOStatement->fetch()
PDOStatement->fetchAll()
PDOStatement->fetchColumn()
PDOStatement->fetchObject()
PDOStatement->getAttribute()
PDOStatement->getColumnMeta()
PDOStatement->nextRowset()
PDOStatement->rowCount()
PDOStatement->setAttribute()
PDOStatement->setFetchMode()
eXTReMe Tracker