<?php $pdo = new PDO('sqlite::memory:'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec('CREATE TABLE t (id INTEGER, name TEXT)'); $pdo->exec("INSERT INTO t VALUES (1, 'a'), (2, 'b'), (3, 'c')"); // each fetch() returns the next row $stmt = $pdo->query('SELECT id, name FROM t ORDER BY id'); var_dump($stmt->fetch(PDO::FETCH_ASSOC)['id'], $stmt->fetch(PDO::FETCH_ASSOC)['id']); // fetchColumn() moves to the next row too var_dump($stmt->fetchColumn()); var_dump($stmt->fetch()); // fetchAll() returns the rest, then nothing $stmt = $pdo->query('SELECT id FROM t ORDER BY id'); $stmt->fetch(); var_dump(count($stmt->fetchAll()), count($stmt->fetchAll())); // fetchObject() and FETCH_CLASS run the constructor, FETCH_FUNC runs a callback class Row { public $id; public function __construct() { echo "constructor runs\n"; } } $stmt = $pdo->query('SELECT id FROM t ORDER BY id'); $stmt->fetchObject(Row::class); $stmt->setFetchMode(PDO::FETCH_CLASS, Row::class); $stmt->fetch(); $stmt = $pdo->query('SELECT id FROM t ORDER BY id'); $stmt->fetchAll(PDO::FETCH_FUNC, function ($id) { echo "callback runs for $id\n"; return $id; });
You have javascript disabled. You will not be able to edit any code.