Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to get the id of an inserted row

Short answer

The lastInsertId() method returns the identifier of the last inserted row:

<?php
 
$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE products (id INTEGER PRIMARY KEY, title TEXT, price INTEGER)');
$pdo->exec("INSERT INTO products (title, price) VALUES ('Tea', 250), ('Coffee', 400), ('Juice', 180), ('Green tea', 300)");
 
$statement = $pdo->prepare('INSERT INTO products (title, price) VALUES (?, ?)');
$statement->execute(['Cocoa', 320]);
 
echo $pdo->lastInsertId();

Output:

5

The identifier is needed to add dependent rows right away:

<?php
 
$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT)');
$pdo->exec('CREATE TABLE order_items (id INTEGER PRIMARY KEY, order_id INTEGER, title TEXT)');
 
$pdo->prepare('INSERT INTO orders (customer) VALUES (?)')->execute(['Anna']);
$orderId = (int) $pdo->lastInsertId();
 
$item = $pdo->prepare('INSERT INTO order_items (order_id, title) VALUES (?, ?)');
 
foreach (['Tea', 'Coffee'] as $title) {
    $item->execute([$orderId, $title]);
}
 
echo $pdo->query("SELECT COUNT(*) FROM order_items WHERE order_id = $orderId")->fetchColumn();

Output:

2

Functions used in this recipe

  • PDO — A database connection.
  • PDOStatement — A prepared statement and its result.
  • intval — Converts a value to an integer.

Thanks for reading!

Donate to the site — we work hard for you.