0

How can I get the ID of the row that I just inserted? I am using a PDO statement where I can insert a name and email into a table.

$dbh = new PDO();
$dbh->prepare ("INSERT INTO `table` (`name`, `email`) VALUES (:name, :email);");
// execute
$dbh->execute(array(':name' => 'John Doe', ':email' => 'johndoe@gmail.com'));

The table also has an auto increment id column.

How can I get the id of the row that was just created? I have read about lastInsertId(), but won't that sometimes give the wrong value if two clients insert a row at the same time?

2 Answers2

1

lastInsertId() returns last inserted id for this DB conection. In other page will be another connection and another last inserted id.

Issam Zoli
  • 2,724
  • 1
  • 21
  • 35
-1

In addition to @Issam Zoli this may be what you need. Seems to have some caveats though.

Check out NaturalBornCamper's Answer.

Here's an example of how to use it from the links above.

$db = new PDO('mysql:dbname=database;host=localhost', 'user', 'pass');
$statement = $this->db->prepare('INSERT INTO people(name, city) VALUES(:name, :city)');
$statement->execute( array(':name' => 'Bob', ':city' => 'Montreal') );

echo $db->lastInsertId();
Community
  • 1
  • 1
Kirk
  • 1,779
  • 14
  • 20