Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check whether a row exists in a database

Short answer

Ask for one row and check whether it came back:

<?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)");
 
function productExists(PDO $pdo, string $title): bool
{
    $statement = $pdo->prepare('SELECT 1 FROM products WHERE title = ? LIMIT 1');
    $statement->execute([$title]);
 
    return $statement->fetchColumn() !== false;
}
 
var_dump(productExists($pdo, 'Tea'));
var_dump(productExists($pdo, 'Milk'));

Output:

bool(true)
bool(false)

Check then insert

Between the check and the insert another request may manage to add the same record. Only a UNIQUE constraint on the table reliably prevents duplicates — the check in code is just for a clear message.

Functions used in this recipe

  • PDO — A database connection.
  • PDOStatement — A prepared statement and its result.
  • boolval — Converts a value to a boolean.

Thanks for reading!

Donate to the site — we work hard for you.