3000 explained code solutions for 75 technologies

php-pdoGet last inserted id with PHP PDO

$st = $pdo->prepare('INSERT INTO test SET name = :name');
$st->execute([':name' => 'Donald']);
$id = $pdo->lastInsertId();ctrl + c

prepare given query to execute


run query on the server


will return last inserted ID of new row (if it's autoincrement)

Usage example


$pdo = new PDO('mysql:host=localhost;dbname=test', 'usr', 'pwd');

$st = $pdo->prepare('INSERT INTO test SET name = :name, age = :age');
$st->execute([':name' => 'Donald', ':age' => 90]);

echo $pdo->lastInsertId();