0

lets say my code is:

$req = $bdd->prepare('INSERT INTO test(name, surname) VALUES(:name, :surname)');
$req->execute(array(
    'name' => $name,
    'surname' => $surname));

And my table test has an auto increment field named id

What is the best way to get the 'id' corresponding to $req?

Ken White
  • 123,280
  • 14
  • 225
  • 444
user2461031
  • 513
  • 2
  • 7
  • 17
  • Are you using MYSQLI or PDO? I would guess PDO, but I want to make sure. –  Sep 02 '13 at 21:31
  • yes, i'm using PDO @MisterMelancholy – user2461031 Sep 02 '13 at 21:31
  • Use the lastInsertId of PDO http://php.net/manual/en/pdo.lastinsertid.php – Virendra Sep 02 '13 at 21:33
  • @Arthur Please be careful when editing code in languages you don't know! `->` and `=>` are atomic operators in PHP. The whitespace you've been trying to add in edits you've been suggesting would BREAK the code...yet they keep getting almost approved by sleepwalking reviewers. Also, please look for posts that actually have things that need *fixing*. These kinds of edits really wouldn't be helpful even if they didn't break the code. – Adi Inbar Sep 02 '13 at 21:40

1 Answers1

3

PDO has a method for this:

$id = $pdo->lastInsertId();

or in your case:

$id = $bdd->lastInsertId();

You can find more information about the lastInsertID method here.

  • So I was wondering, what would happen if multiple DB transactions happened at the same time (multiple users on different computers), would it be possible for the `lastInsertId()` function to return the wrong id??? – James111 Aug 25 '15 at 03:21
  • @James111 I'm not entirely sure what you're asking. `$pdo->lastInsertId()` will return the most recent insert ID of object `$pdo`. –  Aug 29 '15 at 05:26