PDOStatement to JSON

PDOStatement to JSON

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

Stefan Bogdanescu

Founder & Senior Architect

Converting PDOStatement to JSON: A Practical Guide

You are working with a database query result fetched as an object using PDO::FETCH_OBJ. You need that data in JSON format for an API response or a logging system, but you hit a wall: PHP's native json_encode() function cannot directly accept a stdClass instance derived from PDOStatement. While this restriction might seem like a limitation of the language itself, it is actually a consequence of how PDO binds internal database metadata to your objects.

The core issue lies in the nature of the data returned by PDO. When you fetch rows with PDO::FETCH_OBJ, PHP creates a stdClass object where properties are dynamically added based on column names. While this works perfectly for simple CRUD operations, the resulting object often contains hidden attributes that standard JSON serialization cannot handle gracefully. Specifically, PDO objects retain internal metadata about the query execution state and row binding context. If you attempt to pass these directly to json_encode() without preparation, you risk encountering errors or receiving a malformed JSON string containing nulls for internal properties.

To solve this, you must bridge the gap between the raw database driver object and the clean data structure required by JSON standards. The most robust approach involves converting the fetched PDO object into an associative array before serialization. This process strips away the internal metadata while preserving the actual column values.

Consider a scenario where you have executed a query:

$sql = "SELECT id, name, email FROM users WHERE active = 1";
$stmt = $pdo->query($sql);
$stmt->execute();

// Fetch as object
$user = $stmt->fetch(PDO::FETCH_OBJ);

Attempting json_encode($user) immediately will likely fail or produce unexpected results due to the internal state. Instead, you need to iterate over the public properties of the stdClass object and build a clean array:

$jsonData = [];
foreach ((array) $user as $key => $value) {
    // Ensure we only serialize actual data columns, not internal PDO artifacts
    if (is_string($key) && preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $key)) {
        $jsonData[$key] = $value;
    }
}

$jsonOutput = json_encode($jsonData);

The regex check in the loop ensures that only valid column names are included, filtering out any potential internal properties PDO might have attached. This manual mapping guarantees that the resulting JSON is compliant and safe to transmit over HTTP.

However, this manual conversion adds verbosity to your code. If you are working within a Laravel application, you can leverage the framework's collection utilities to simplify this pattern. By wrapping the result in a Collection, you gain access to methods like pluck or simple casting that handle the conversion more elegantly:

$users = $pdo->query($sql)->fetchAll(PDO::FETCH_OBJ);
$usersArray = array_map(function ($user) {
    return (array) $user;
}, $users);

$jsonOutput = json_encode($usersArray);

Alternatively, using array_values or casting the entire object to an array can often suffice if you are certain no internal properties exist. The trade-off here is performance versus code clarity. For high-throughput APIs, the overhead of iterating through every row and mapping it might be significant compared to fetching as an associative array initially.

If you anticipate needing this conversion frequently, consider fetching the data directly into an associative array using PDO::FETCH_ASSOC from the start. This eliminates the need for post-processing entirely:

$assocUser = $stmt->fetch(PDO::FETCH_ASSOC);
$jsonOutput = json_encode($assocUser);

This approach is generally preferred in modern PHP development because it keeps the data in a native array structure, making it compatible with json_encode() out of the box. While fetching as objects (PDO::FETCH_OBJ) offers convenient access via property syntax (e.g., $user->name), the extra step required to convert that object to JSON often negates the convenience benefit when dealing with API responses.

If you are managing a larger codebase or maintaining legacy systems where PDO::FETCH_OBJ is deeply entrenched, understanding this conversion mechanism becomes essential. The LaravelCompany documentation often highlights best practices for handling data serialization in enterprise applications, emphasizing the importance of clean data structures before entering the JSON pipeline. Ensuring your data is an associative array before encoding prevents subtle bugs that can arise from hidden object properties or null values injected by the database driver.

Our network