0
0
PHPprogramming~10 mins

Fetching results (fetch, fetchAll) in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to fetch one row from the PDO statement.

PHP
<?php
$stmt = $pdo->query('SELECT * FROM users');
$row = $stmt->[1]();
print_r($row);
?>
Drag options to blanks, or click blank then click option'
Afetch
BfetchAll
Cexecute
Dprepare
Attempts:
3 left
💡 Hint
Common Mistakes
Using fetchAll() when only one row is needed.
Using execute() which runs a statement but does not fetch data.
2fill in blank
medium

Complete the code to fetch all rows from the PDO statement.

PHP
<?php
$stmt = $pdo->query('SELECT * FROM products');
$rows = $stmt->[1]();
foreach ($rows as $row) {
    echo $row['name'] . "\n";
}
?>
Drag options to blanks, or click blank then click option'
Afetch
Bexecute
CfetchAll
Dprepare
Attempts:
3 left
💡 Hint
Common Mistakes
Using fetch() when all rows are needed.
Using execute() which does not fetch data.
3fill in blank
hard

Fix the error in fetching rows as associative arrays.

PHP
<?php
$stmt = $pdo->query('SELECT id, email FROM users');
$rows = $stmt->fetchAll([1]);
foreach ($rows as $row) {
    echo $row['email'] . "\n";
}
?>
Drag options to blanks, or click blank then click option'
APDO::FETCH_ASSOC
BPDO::FETCH_OBJ
CPDO::FETCH_NUM
DPDO::FETCH_BOTH
Attempts:
3 left
💡 Hint
Common Mistakes
Using FETCH_NUM which returns numeric keys.
Using FETCH_OBJ which returns objects instead of arrays.
4fill in blank
hard

Fill both blanks to fetch rows as objects and print a property.

PHP
<?php
$stmt = $pdo->query('SELECT id, username FROM users');
$rows = $stmt->[1]([2]);
foreach ($rows as $user) {
    echo $user->username . "\n";
}
?>
Drag options to blanks, or click blank then click option'
AfetchAll
Bfetch
CPDO::FETCH_OBJ
DPDO::FETCH_ASSOC
Attempts:
3 left
💡 Hint
Common Mistakes
Using fetch() instead of fetchAll() to get all rows.
Using FETCH_ASSOC which returns arrays, not objects.
5fill in blank
hard

Fill all three blanks to fetch one row as a numeric array and print the first column.

PHP
<?php
$stmt = $pdo->query('SELECT id, name FROM categories');
$row = $stmt->[1]([2]);
echo $row[[3]];
?>
Drag options to blanks, or click blank then click option'
AfetchAll
Bfetch
C0
DPDO::FETCH_NUM
Attempts:
3 left
💡 Hint
Common Mistakes
Using fetchAll() when only one row is needed.
Using FETCH_ASSOC which returns associative arrays.
Using wrong index to access the first column.