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
$pdo->prepare

prepare given query to execute

$st->execute(

run query on the server

$pdo->lastInsertId

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


Usage example

<?php

$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();
output
7