The Reality of Checking Row Existence in PDO
When building logic that depends on data availability, developers often start by querying a row and then trying to determine if it exists based on the result. A common scenario involves checking for a specific ID using SELECT and attempting to validate the outcome immediately after fetching. You might find yourself staring at code like this:
$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (count($row) == 0) { /* row does not exist */ }
if ($stmt->rowCount() < 0) { /* row does not exist */ }
In the example above, both approaches fail to provide the correct behavior. The first attempt checks count($row), but $row is an associative array containing the columns of a single record. If the query returns no rows, fetch() simply returns false. While count(false) might technically return 0 in some contexts depending on PHP version or specific implementation quirks, relying on counting a boolean result is semantically incorrect and fragile. The second attempt relies on rowCount(), which is notoriously misleading for SELECT statements.
The core issue lies in understanding what rowCount() actually measures. For SELECT queries, PDO's rowCount() method returns 0 by default unless the underlying database driver explicitly supports reporting the number of rows affected or selected. Even then, many drivers (like MySQLi or certain PostgreSQL configurations) return -1 for SELECT statements because they cannot know how many rows exist until the entire result set is processed or streamed. Consequently, checking if rowCount() is less than zero is not a reliable indicator of data presence; it often just tells you that the driver didn't report the count, not that the row was missing.
To reliably check if a row exists in the database using PDO, you must treat the return value of fetch() as your source of truth. When you execute a query and call fetch(), the method returns an array containing the column data if a row is found, or false if no rows match the condition. This behavior is consistent across standard PDO drivers.
The correct implementation looks like this:
$stmt = $conn->prepare('SELECT * FROM table WHERE ID = ?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row === false) {
// The row does not exist
} else {
// The row exists; $row contains the data
}
By comparing $row strictly to false, you are checking the actual return value of the fetch operation. This approach works because fetch() is designed to distinguish between a successful row retrieval (array) and an empty result set (false). If you need to access properties of the row, ensure you do so only within the else block or after verifying that $row is not false.
There are trade-offs to consider when implementing this logic. One significant performance factor is whether you need the data itself. If your application logic only cares about existence and does not require any column values from that row, selecting all columns with SELECT * adds unnecessary overhead. In such cases, a more efficient query would be:
$stmt = $conn->prepare('SELECT ID FROM table WHERE ID = ?');
$stmt->execute([$_GET['id']]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
Here, you still use fetch() to check for existence, but the database engine performs a simpler lookup. Another consideration is error handling. If the ID provided in the request is malformed or causes an SQL syntax error, your application will throw an exception rather than returning false. Always wrap database operations in try-catch blocks if your environment expects graceful degradation rather than fatal errors.
While raw PDO offers fine-grained control over this logic, frameworks like Laravel simplify these checks significantly. The Eloquent ORM provides methods such as where('id', $id)->exists(), which return a boolean directly without requiring manual fetch handling. This abstraction reduces boilerplate code and minimizes the risk of misinterpreting fetch() return values. For developers maintaining legacy codebases or those who prefer direct SQL for performance reasons, understanding the fetch() return value remains essential for writing robust persistence logic.