📖 Scenario: You are building a simple PHP script to get user data from a database. You want to learn how to fetch one row at a time and how to fetch all rows at once.
🎯 Goal: Learn how to use fetch() and fetchAll() methods to get data from a database query result.
📋 What You'll Learn
Create a PDO connection to an SQLite in-memory database
Create a table called users with columns id, name, and email
Insert three users with exact data
Use fetch() to get one user row
Use fetchAll() to get all user rows
Print the fetched results
💡 Why This Matters
🌍 Real World
Fetching data from databases is a common task in web development. Knowing how to get one row or all rows helps you display data efficiently.
💼 Career
Many jobs require working with databases and PHP. Understanding fetch methods is essential for backend development and data handling.
Progress0 / 4 steps
1
Create the database and insert users
Create a PDO connection called $pdo to an SQLite in-memory database. Then create a table called users with columns id (integer primary key), name (text), and email (text). Insert these three users exactly: (1, 'Alice', 'alice@example.com'), (2, 'Bob', 'bob@example.com'), and (3, 'Charlie', 'charlie@example.com').
PHP
Hint
Use new PDO('sqlite::memory:') to create the database. Use exec() to run SQL commands.
2
Prepare a SELECT query
Create a variable called $stmt that prepares the SQL query SELECT * FROM users using the $pdo connection.
PHP
Hint
Use $pdo->prepare() with the exact SQL string.
3
Fetch one user row using fetch()
Execute the prepared statement $stmt. Then create a variable called $oneUser that fetches one row using fetch() with PDO::FETCH_ASSOC to get an associative array.
PHP
Hint
Call execute() before fetching. Use fetch(PDO::FETCH_ASSOC) to get one row as an associative array.
4
Fetch all user rows using fetchAll() and print results
Create a variable called $allUsers that fetches all rows using fetchAll() with PDO::FETCH_ASSOC. Then print $oneUser and $allUsers using print_r().
PHP
Hint
Use fetchAll(PDO::FETCH_ASSOC) to get all rows as an array of associative arrays. Use print_r() to display arrays.
Practice
(1/5)
1. What does the fetch() method do when used with a PDO statement in PHP?
easy
A. Retrieves one row from the query result
B. Retrieves all rows from the query result
C. Executes the SQL query
D. Closes the database connection
Solution
Step 1: Understand the purpose of fetch()
The fetch() method is designed to get a single row from the result set of a database query.
Step 2: Compare with other methods
Unlike fetchAll(), which retrieves all rows, fetch() only returns one row at a time.
Final Answer:
Retrieves one row from the query result -> Option A
Quick Check:
fetch() = one row [OK]
Hint: fetch() gets one row, fetchAll() gets all rows [OK]
Common Mistakes:
Confusing fetch() with fetchAll()
Thinking fetch() executes the query
Assuming fetch() closes the connection
2. Which of the following is the correct syntax to fetch all rows from a PDO statement $stmt in PHP?
easy
A. $rows = $stmt->fetchAll();
B. $rows = $stmt->fetch_all();
C. $rows = fetchAll($stmt);
D. $rows = $stmt->fetch();
Solution
Step 1: Identify the correct method name
The PDOStatement object uses fetchAll() 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 A
Quick Check:
fetchAll() method syntax correct [OK]
Hint: Use fetchAll() with parentheses on the statement object [OK]
Common Mistakes:
Using fetch_all() instead of fetchAll()
Calling fetchAll() as a standalone function
Using fetch() when fetchAll() is needed
3. Given the following PHP code, what will be the output?
$stmt = $pdo->query('SELECT id FROM users LIMIT 2');
$row1 = $stmt->fetch();
$row2 = $stmt->fetch();
$row3 = $stmt->fetch();
var_dump([$row1, $row2, $row3]);
medium
A. [false, false, false]
B. [array with first row, array with second row, array with third row]
C. [array with first row, array with second row, false]
D. Syntax error
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 C
Quick Check:
fetch() returns false after last row [OK]
Hint: fetch() returns false when no rows left [OK]
Common Mistakes:
Expecting fetch() to return null instead of false
Assuming fetch() returns empty array after last row
Thinking fetch() fetches all rows at once
4. What is wrong with this PHP code snippet?
$stmt = $pdo->query('SELECT name FROM users');
$rows = $stmt->fetch();
foreach ($rows as $row) {
echo $row['name'];
}
medium
A. fetch() returns all rows, so foreach is unnecessary
B. The variable $rows is not defined
C. The query syntax is invalid
D. fetch() returns a single row, so foreach on it causes error
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 D
Quick Check:
fetch() = one row, foreach needs multiple rows [OK]
Hint: Use fetchAll() when looping over multiple rows [OK]
Common Mistakes:
Using fetch() when fetchAll() is needed for loops
Assuming fetch() returns all rows
Not checking data structure before foreach
5. You want to fetch all users from the database but only keep those whose age is greater than 18. Which code snippet correctly uses fetchAll() with a filter in PHP?
hard
A. $adults = $stmt->fetchAll(fn($r) => $r['age'] > 18);