Appearance
How to check if a row exist in the database using PDO?
You can check if a row exists in the database using PDO by fetching a single row or counting the results. While rowCount() is sometimes used, it is not recommended for SELECT queries because its behavior is driver-dependent and often unreliable.
Example of using fetch() to check if a row exists
php
$stmt = $pdo->prepare("SELECT * FROM table_name WHERE column = :value");
$stmt->execute(['value' => $value]);
if ($stmt->fetch()) {
// row exists
} else {
// row does not exist
}Example of using COUNT(*) to check if a row exists
php
$stmt = $pdo->prepare("SELECT COUNT(*) FROM table_name WHERE column = :value");
$stmt->execute(['value' => $value]);
if ($stmt->fetchColumn() > 0) {
// row exists
} else {
// row does not exist
}Note that rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object. For SELECT statements, some databases may return the number of rows returned, however, it's not guaranteed to work across all PDO drivers. This is particularly unreliable on unbuffered MySQL connections, where it may return 0 even when rows are present. For a reliable row existence check, use $stmt->fetch() or SELECT COUNT(*) instead.