Search code examples
phpsqlpdoauto-increment

Get the last auto increment id


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?


Solution

  • 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.