PDO fetch modes
| FETCH_ASSOC | |
| FETCH_CLASS | |
| FETCH_COLUMN | |
| Lazy cursors note |
FETCH_ASSOC
Assoc mode returns each row as an array keyed by column name. It is the clearest default for templates and JSON output.
Fetch all rows at once for small results, and loop row by row for larger sets.
$stmt = $pdo->query("SELECT id, amount FROM ledger"); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($rows as $row) { echo $row["id"]; echo $row["amount"]; }
FETCH_CLASS
Class mode builds an object of the given type for every row. Column values fill matching public properties by name.
This form keeps business code tidy, because rows arrive as typed models instead of plain arrays.
class LedgerRow { public int $id = 0; public int $amount = 0; } $stmt = $pdo->query("SELECT id, amount FROM ledger"); $rows = $stmt->fetchAll(PDO::FETCH_CLASS, LedgerRow::class); echo $rows[0]->amount;
FETCH_COLUMN
Column mode returns a flat list of values from one column. It fits id lists, names, and totals without extra wrapping.
Pass the column index starting from zero to pick which field becomes the plain value.
$stmt = $pdo->query("SELECT amount FROM ledger"); $amounts = $stmt->fetchAll(PDO::FETCH_COLUMN, 0); var_dump($amounts);
Lazy cursors note
Large results should stream through a cursor instead of loading all rows at once. Fetch inside a loop and close the cursor when done.
This keeps memory flat while processing thousands of rows in background jobs.
$stmt = $pdo->query("SELECT id, amount FROM ledger"); while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) { echo $row["id"]; } $stmt->closeCursor();
Next: cURL requests
Article author: Arthur Isaev