PDO Fetch Modes
PDO supports many fetch modes: FETCH_ASSOC (array), FETCH_OBJ (stdClass), FETCH_CLASS (custom class), FETCH_COLUMN (single column), FETCH_KEY_PAIR (key=>value pairs).
PDO supports many fetch modes: FETCH_ASSOC (array), FETCH_OBJ (stdClass), FETCH_CLASS (custom class), FETCH_COLUMN (single column), FETCH_KEY_PAIR (key=>value pairs).
<?php
$stmt = $pdo->query("SELECT id, name, email FROM users");
// FETCH_ASSOC: ["id"=>1, "name"=>"Alice"]
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// FETCH_OBJ: $row->name
$rows = $stmt->fetchAll(PDO::FETCH_OBJ);
// FETCH_CLASS: maps to User properties
$users = $stmt->fetchAll(PDO::FETCH_CLASS, User::class);
// FETCH_COLUMN: just the first column
$names = $stmt->fetchAll(PDO::FETCH_COLUMN, 0); // ["Alice", "Bob"]
// FETCH_KEY_PAIR: ["id" => "name"] map
$idToName = $stmt->fetchAll(PDO::FETCH_KEY_PAIR); // [1=>"Alice", 2=>"Bob"]
FETCH_KEY_PAIR is great for building lookup maps — select id and name to get a quick [id => name] array.