Skip to main content

Lesson 5 of 7

Fetching Strategies - FETCH_CLASS & Hydration

PDO can map query results directly to class instances using FETCH_CLASS - eliminating the manual array-to-object mapping step. Understanding PDO's fetch modes and mapping query results to domain objects (hydration) is essential for clean repository implementations.

11 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

PDO Fetch Modes & Object Hydration

PDO Fetch Modes & Object Hydration
<?php
declare(strict_types=1);

// ── PDO::FETCH_ASSOC - associative array (default) ────────────
$stmt = $pdo->query("SELECT id, title, status FROM posts");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// [["id" => 1, "title" => "...", "status" => "..."], ...]

// ── PDO::FETCH_CLASS - directly into objects ──────────────────
class PostRow {
    public int    $id;
    public string $title;
    public string $status;
    public string $author_name;
    // PDO sets properties BEFORE constructor (use FETCH_PROPS_LATE for after)
}

$stmt = $pdo->prepare(
    "SELECT p.id, p.title, p.status, u.name AS author_name
     FROM posts p JOIN users u ON u.id = p.author_id WHERE p.id = :id"
);
$stmt->execute([":id" => 1]);
$stmt->setFetchMode(PDO::FETCH_CLASS, PostRow::class);
$post = $stmt->fetch();   // returns PostRow instance
echo $post->title;        // "PHP Basics"
echo $post->author_name;  // "Alice"

// Fetch all as objects
$stmt = $pdo->query("SELECT id, title, status FROM posts WHERE status = 'published'");
$posts = $stmt->fetchAll(PDO::FETCH_CLASS, PostRow::class);

// ── Manual hydration - map array to Domain Object ────────────
// (Preferred in layered architecture - keeps Domain clean)
class PdoPostRepository {
    public function findById(int $id): ?Post {
        $stmt = $this->pdo->prepare(
            "SELECT p.id, p.title, p.slug, p.body, p.status, p.created_at,
                    u.name AS author_name, u.email AS author_email
             FROM posts p
             JOIN users u ON u.id = p.author_id
             WHERE p.id = :id LIMIT 1"
        );
        $stmt->execute([":id" => $id]);
        $row = $stmt->fetch();
        if ($row === false) return null;
        return $this->hydrate($row);
    }

    private function hydrate(array $row): Post {
        return new Post(
            id:     (int) $row["id"],
            title:  $row["title"],
            slug:   $row["slug"],
            body:   $row["body"],
            status: PostStatus::from($row["status"]),
            author: new Author($row["author_name"], new Email($row["author_email"])),
        );
    }
}

// ── fetchColumn - single scalar value ─────────────────────────
$count    = $pdo->query("SELECT COUNT(*) FROM posts")->fetchColumn();    // "42"
$maxViews = $pdo->query("SELECT MAX(views) FROM posts")->fetchColumn();   // "5000"
$title    = $pdo->query("SELECT title FROM posts WHERE id = 1")->fetchColumn(0);

// ── PDO::FETCH_KEY_PAIR - key => value map ────────────────────
$idToTitle = $pdo->query("SELECT id, title FROM posts")->fetchAll(PDO::FETCH_KEY_PAIR);
// [1 => "PHP Basics", 2 => "PDO Guide", ...]
echo $idToTitle[2];   // "PDO Guide"

Quick Quiz

Tip

Tip

Practice Fetching Strategies FETCHCLASS Hydration in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Fetching Strategies - FETCH_CLASS & Hydration

Practice Task

Note

Practice Task - (1) Write a working example of Fetching Strategies FETCHCLASS Hydration from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Fetching Strategies FETCHCLASS Hydration is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done