Fetching results lets you get data from a database after running a query. It helps you use that data in your PHP program.
Fetching results (fetch, fetchAll) in PHP
$stmt = $pdo->query('SELECT * FROM table');
$row = $stmt->fetch();
$allRows = $stmt->fetchAll();fetch() gets one row at a time from the result.
fetchAll() gets all rows at once as an array.
$stmt = $pdo->query('SELECT name FROM users'); $row = $stmt->fetch(); echo $row['name'];
$stmt = $pdo->query('SELECT name FROM users'); $allUsers = $stmt->fetchAll(); foreach ($allUsers as $user) { echo $user['name'] . "\n"; }
This program creates a small users table, inserts three names, then fetches the first user with fetch(). Next, it fetches all remaining users with fetchAll() and prints their names.
<?php // Connect to SQLite in memory for example $pdo = new PDO('sqlite::memory:'); // Create a sample table $pdo->exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)"); // Insert sample data $pdo->exec("INSERT INTO users (name) VALUES ('Alice'), ('Bob'), ('Charlie')"); // Query the table $stmt = $pdo->query('SELECT * FROM users'); // Fetch one row $firstUser = $stmt->fetch(); echo "First user: " . $firstUser['name'] . "\n"; // Fetch all remaining rows $allUsers = $stmt->fetchAll(); echo "All users after first:\n"; foreach ($allUsers as $user) { echo $user['name'] . "\n"; }
After calling fetch(), the internal pointer moves forward, so fetchAll() gets the remaining rows.
If you want all rows at once, just use fetchAll() without calling fetch() first.
Always check if the query succeeded before fetching results to avoid errors.
fetch() gets one row from the query result.
fetchAll() gets all rows as an array.
Use these to get data from your database queries and work with it in PHP.
Practice
fetch() method do when used with a PDO statement in PHP?Solution
Step 1: Understand the purpose of
Thefetch()fetch()method is designed to get a single row from the result set of a database query.Step 2: Compare with other methods
UnlikefetchAll(), which retrieves all rows,fetch()only returns one row at a time.Final Answer:
Retrieves one row from the query result -> Option AQuick Check:
fetch()= one row [OK]
- Confusing fetch() with fetchAll()
- Thinking fetch() executes the query
- Assuming fetch() closes the connection
$stmt in PHP?Solution
Step 1: Identify the correct method name
The PDOStatement object usesfetchAll()to retrieve all rows as an array.Step 2: Check method call syntax
The correct syntax is$stmt->fetchAll();with camelCase and parentheses.Final Answer:
$rows = $stmt->fetchAll(); -> Option AQuick Check:
fetchAll() method syntax correct [OK]
- Using fetch_all() instead of fetchAll()
- Calling fetchAll() as a standalone function
- Using fetch() when fetchAll() is needed
$stmt = $pdo->query('SELECT id FROM users LIMIT 2');
$row1 = $stmt->fetch();
$row2 = $stmt->fetch();
$row3 = $stmt->fetch();
var_dump([$row1, $row2, $row3]);Solution
Step 1: Understand fetch() behavior on limited rows
The query returns 2 rows. Each fetch() call returns one row until no rows remain.Step 2: Analyze each fetch() call
First fetch() returns first row array, second fetch() returns second row array, third fetch() returns false (no more rows).Final Answer:
[array with first row, array with second row, false] -> Option CQuick Check:
fetch() returns false after last row [OK]
- Expecting fetch() to return null instead of false
- Assuming fetch() returns empty array after last row
- Thinking fetch() fetches all rows at once
$stmt = $pdo->query('SELECT name FROM users');
$rows = $stmt->fetch();
foreach ($rows as $row) {
echo $row['name'];
}Solution
Step 1: Check what fetch() returns
fetch() returns a single row as an array, not an array of rows.Step 2: Understand foreach usage
foreach expects an array of rows, but here it loops over columns of one row, causing errors when accessing $row['name'].Final Answer:
fetch() returns a single row, so foreach on it causes error -> Option DQuick Check:
fetch() = one row, foreach needs multiple rows [OK]
- Using fetch() when fetchAll() is needed for loops
- Assuming fetch() returns all rows
- Not checking data structure before foreach
age is greater than 18. Which code snippet correctly uses fetchAll() with a filter in PHP?Solution
Step 1: Fetch all rows first
UsefetchAll()to get all rows as an array.Step 2: Filter rows by age
Usearray_filter()with a callback to keep only rows whereage > 18.Final Answer:
$rows = $stmt->fetchAll(); $adults = array_filter($rows, fn($r) => $r['age'] > 18); -> Option BQuick Check:
fetchAll() + array_filter() = filtered rows [OK]
- Passing a callback directly to fetchAll() (not supported)
- Modifying array inside foreach without reassigning
- Using fetch() when multiple rows needed
Ready to prove it?
Pass the test and this pattern moves unknown
