PDO get data from database

PDO get data from database

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

Stefan Bogdanescu

Founder & Senior Architect

Why Your PDO Fetch Loop Returns Blank on Screen

When migrating from procedural MySQL functions to PDO, it is common to encounter situations where the code executes without throwing an exception, yet produces no visible output. The snippet provided in your query demonstrates a typical pattern for retrieving data: preparing a statement, fetching all rows into memory, checking the count, and then iterating through the result set.

However, there is a critical distinction between PHP executing successfully and PHP actually displaying data to the browser. The most frequent cause of a "blank page" in this scenario is not with the PDO logic itself, but with the HTTP response headers. If you are using a framework like Laravel or any custom routing system, output buffering or middleware might be intercepting your echo statements before they reach the client. Conversely, in a raw PHP script, if header('Content-Type: text/html') has not been sent prior to any whitespace (including newlines) being written to the output buffer, the browser will treat the response as plain text. While this usually results in garbled HTML, it is less likely to cause a total blank page unless the entire file is treated as binary or if an earlier script tag closed the document.

More likely, the issue lies within the conditional logic and how the result set is being inspected. The line if(count($getUsers) > 0) attempts to check if data exists before entering the loop. While this pattern works for procedural MySQL, it can be misleading with PDO when combined with fetchAll().

The method fetchAll() returns a complete array of rows and advances the internal cursor of the PDOStatement to the end. This is generally safe, but relying on count() on that array assumes the query executed successfully without errors. If the database connection $DBH is not properly configured—for instance, if the DSN, username, or password are incorrect—the query will fail silently depending on how error modes are set (e.g., PDO::ERRMODE_SILENT). In a production environment, you should explicitly enable exceptions with try { $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } to ensure that any SQL syntax errors or connection failures halt execution immediately.

Consider this refined implementation:

$DBH = new PDO("mysql:host=localhost;dbname=test", "user", "pass");
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try {
    $getUsers = $DBH->prepare("SELECT id, username FROM users ORDER BY id ASC");
    $getUsers->execute(); // Explicitly execute before fetching
    
    if ($getUsers->rowCount() > 0) {
        while ($user = $getUsers->fetch(PDO::FETCH_ASSOC)) {
            echo htmlspecialchars($user['username']) . "<br>";
        }
    } else {
        echo "No users found."; // Use echo instead of undefined error() function
    }
} catch (PDOException $e) {
    // Log $e->getMessage() to a file or send an email, do not dump directly in production
    die('Database error occurred.'); 
}

By switching to rowCount() after execution but before fetching all rows, you avoid loading the entire dataset into memory just to check for existence. This is particularly important when dealing with large tables containing thousands of records. Furthermore, using htmlspecialchars() on output prevents XSS vulnerabilities when echoing user-generated content like usernames directly to an HTML page.

If you are still seeing a blank page after verifying the database contains users and the credentials are correct, inspect the PHP error log. Sometimes, errors regarding missing functions (like your custom error() function) or undefined variables in the script will trigger a fatal error that halts execution before any output is rendered. Ensure that your helper functions are defined globally or within the scope of the current file.

For developers moving towards modern stacks, understanding how PDO interacts with frameworks like Laravel is essential. In Laravel, database queries are often handled via Eloquent ORM rather than raw PDO statements, which abstracts away much of this manual fetching logic. If you require deeper integration with a robust framework that handles connection pooling and migrations out of the box, LaravelCompany provides resources on leveraging their specific tools to streamline database interactions beyond basic PDO usage.

Our network