Checking for an empty result (PHP, PDO, and MySQL)

Checking for an empty result (PHP, PDO, and MySQL)

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

The State of Your Cursor: Why Checking fetchColumn() Breaks Your Loop

It is a common pattern in legacy PHP code to iterate through database results and populate an array, often assuming data exists. However, checking whether that result set is empty before processing requires care with how PDO handles its cursor. Consider this scenario: you have a working query that retrieves emails for hard copies sent today. The first version of your code fetches every row inside a while loop and adds it to $this->id_email. This works as expected.

The moment you introduce a guard clause using $sth->fetchColumn() to detect an empty result set, the behavior changes drastically. You might expect this check to simply return a boolean based on whether a row exists. Instead, your code returns 'empty' and fails to yield the matching results that were previously returned. This isn't a logic error in your SQL; it is a side effect of how PDO's fetch methods modify the internal state of the statement object.

How fetchColumn Advances the Cursor

The core issue lies in the behavior of $sth->fetch() and its variants. When you call any fetch method on a PDOStatement, it does not just read data; it advances the internal cursor to the next row. If you want to inspect the first row without consuming it, you must use a specific fetch mode that returns data without moving past the current position—or rather, before moving past the first row.

In your second code snippet, the line $sth->fetchColumn() is executed immediately after execute(). At this exact moment, the cursor is positioned at the first row. Calling fetchColumn reads that first row and advances the cursor to the second row (or the end of the result set if there was only one).

Consequently, when you enter the subsequent while ($row = $sth->fetch(PDO::FETCH_ASSOC)) loop, the cursor is already past the first record. The loop attempts to read from the current position, finds nothing (because the data has been consumed), and immediately exits. The result set appears empty not because the query failed, but because you have already iterated over it once.

The Correct Approach for Guard Clauses

To check if a result set is empty without losing data, you must use fetchColumn with a mode that returns false on the first call if no rows exist, but does not permanently consume the stream in a way that breaks subsequent loops. However, the safest and most idiomatic approach in PDO is to rely on rowCount() or to handle the initial fetch within the loop logic itself.

Using fetchColumn without arguments often behaves differently depending on the driver and whether the cursor was positioned at the start. A more robust pattern for checking emptiness while preserving the data stream is to use fetchColumn with a specific flag or, even better, to check rowCount() after execution if your database driver supports it (MySQLi does not reliably support rowCount(), but PDO MySQL often returns 0 before fetching unless emulated).

If you specifically need to know if there are rows before iterating, the most reliable method without relying on cursor state tricks is to check fetchColumn in a way that doesn't disrupt the loop. Actually, the cleanest solution for your specific case is to simply let the while loop handle the empty case naturally.

If you must check upfront, consider using fetchColumn with PDO::FETCH_COLUMN but ensuring you don't rely on the cursor position for the main loop. Alternatively, you can use rowCount() after execution. In many PDO implementations, $sth->rowCount() returns -1 or 0 before any rows are fetched, making it unreliable for pre-checking emptiness in MySQL.

The most pragmatic fix is to restructure the logic to not assume the cursor state remains static between checks. If you call fetchColumn(), you are consuming the first row. You can reconstruct the array by starting from the second row, but that is inefficient and semantically confusing. Instead, simply remove the pre-loop check. The while loop condition handles the empty case perfectly:

if (!$sth->execute()) {
    $db = null;
    exit();
}

// No need to check for emptiness here. 
// If there are no rows, the loop body never executes.
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    $this->id_email[] = $row['id_email'];
    echo $row['id_email'];
}

$db = null;
return true; // Or false depending on your application's requirements for empty sets

This approach eliminates the side effect of consuming the first row. If you absolutely require a boolean return value based on existence, capture the result of the initial fetch into a variable and use that:

$firstRow = $sth->fetch(PDO::FETCH_ASSOC);
if ($firstRow) {
    // Data exists, process all rows including the one just fetched
    $this->id_email[] = $firstRow['id_email'];
    
    while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
        $this->id_email[] = $row['id_email'];
        echo $row['id_email'];
    }
} else {
    // Result set was empty initially
}

By explicitly capturing the first row, you acknowledge its existence without letting the cursor state dictate your loop logic unexpectedly. This ensures that every row is processed exactly once, regardless of how you choose to structure your conditional checks.

Our network