Bird
Raised Fist0
PHPprogramming~20 mins

Fetching results (fetch, fetchAll) in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
PDO Fetch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this PHP code using fetch()?

Consider the following PHP code that queries a database and fetches one row:

$stmt = $pdo->query('SELECT id, name FROM users ORDER BY id LIMIT 1');
$row = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($row);

What will be printed?

PHP
$stmt = $pdo->query('SELECT id, name FROM users ORDER BY id LIMIT 1');
$row = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($row);
AArray with numeric keys 0 and 1 containing the first user's data
BArray with keys 'id' and 'name' containing the first user's data
CBoolean false
DAn error message about fetchAll()
Attempts:
2 left
💡 Hint

fetch() returns one row as an associative array if you use PDO::FETCH_ASSOC.

❓ Predict Output
intermediate
2:00remaining
What does fetchAll() return in this PHP example?

Given this PHP code snippet:

$stmt = $pdo->query('SELECT id, name FROM users');
$rows = $stmt->fetchAll(PDO::FETCH_NUM);
print_r($rows);

What is the structure of $rows?

PHP
$stmt = $pdo->query('SELECT id, name FROM users');
$rows = $stmt->fetchAll(PDO::FETCH_NUM);
print_r($rows);
AAn array of arrays with numeric keys for each row
BAn array of associative arrays with column names as keys
CA single associative array with all rows merged
DBoolean false
Attempts:
2 left
💡 Hint

PDO::FETCH_NUM returns numeric keys for columns.

❓ Predict Output
advanced
2:00remaining
What error does this PHP code raise?

Analyze this PHP code snippet:

$stmt = $pdo->query('SELECT id, name FROM users');
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($row[0]['nonexistent_column']);

What error will occur?

PHP
$stmt = $pdo->query('SELECT id, name FROM users');
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($row[0]['nonexistent_column']);
ANo error, prints null
BFatal error: Call to undefined method fetchAll()
CTypeError because fetchAll returns boolean
DUndefined index notice for 'nonexistent_column'
Attempts:
2 left
💡 Hint

Accessing an array key that does not exist triggers a notice.

❓ Predict Output
advanced
2:00remaining
What is the output of this PHP code using fetch() with PDO::FETCH_OBJ?

Consider this PHP code:

$stmt = $pdo->query('SELECT id, name FROM users ORDER BY id LIMIT 1');
$user = $stmt->fetch(PDO::FETCH_OBJ);
echo $user->name;

What will be printed?

PHP
$stmt = $pdo->query('SELECT id, name FROM users ORDER BY id LIMIT 1');
$user = $stmt->fetch(PDO::FETCH_OBJ);
echo $user->name;
AThe name of the first user as a string
BAn array containing the user's name
CBoolean false
DFatal error: Cannot access property on non-object
Attempts:
2 left
💡 Hint

PDO::FETCH_OBJ returns an object with properties matching column names.

🧠 Conceptual
expert
2:00remaining
How many items are in the array returned by fetchAll() after this query?

Given a table products with 5 rows, what is the number of elements in the array returned by this PHP code?

$stmt = $pdo->query('SELECT * FROM products');
$allProducts = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo count($allProducts);
A0
B1
C5
DAn error occurs
Attempts:
2 left
💡 Hint

fetchAll() returns all rows as an array of 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

  1. 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.
  2. Step 2: Compare with other methods

    Unlike fetchAll(), which retrieves all rows, fetch() only returns one row at a time.
  3. Final Answer:

    Retrieves one row from the query result -> Option A
  4. 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

  1. Step 1: Identify the correct method name

    The PDOStatement object uses fetchAll() to retrieve all rows as an array.
  2. Step 2: Check method call syntax

    The correct syntax is $stmt->fetchAll(); with camelCase and parentheses.
  3. Final Answer:

    $rows = $stmt->fetchAll(); -> Option A
  4. 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

  1. Step 1: Understand fetch() behavior on limited rows

    The query returns 2 rows. Each fetch() call returns one row until no rows remain.
  2. 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).
  3. Final Answer:

    [array with first row, array with second row, false] -> Option C
  4. 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

  1. Step 1: Check what fetch() returns

    fetch() returns a single row as an array, not an array of rows.
  2. 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'].
  3. Final Answer:

    fetch() returns a single row, so foreach on it causes error -> Option D
  4. 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);
B. $rows = $stmt->fetchAll(); $adults = array_filter($rows, fn($r) => $r['age'] > 18);
C. $adults = $stmt->fetchAll(); foreach ($adults as $r) { if ($r['age'] <= 18) unset($r); }
D. $adults = $stmt->fetch(); while ($r['age'] > 18) { $adults[] = $r; }

Solution

  1. Step 1: Fetch all rows first

    Use fetchAll() to get all rows as an array.
  2. Step 2: Filter rows by age

    Use array_filter() with a callback to keep only rows where age > 18.
  3. Final Answer:

    $rows = $stmt->fetchAll(); $adults = array_filter($rows, fn($r) => $r['age'] > 18); -> Option B
  4. Quick Check:

    fetchAll() + array_filter() = filtered rows [OK]
Hint: fetchAll() then filter with array_filter() for conditions [OK]
Common Mistakes:
  • Passing a callback directly to fetchAll() (not supported)
  • Modifying array inside foreach without reassigning
  • Using fetch() when multiple rows needed
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard