0
0
PHPprogramming~10 mins

Fetch modes and styles 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 a row as an associative array using PDO.

PHP
<?php
$stmt = $pdo->query('SELECT * FROM users');
$row = $stmt->fetch([1]);
print_r($row);
?>
Drag options to blanks, or click blank then click option'
APDO::FETCH_BOTH
BPDO::FETCH_NUM
CPDO::FETCH_ASSOC
DPDO::FETCH_OBJ
Attempts:
3 left
💡 Hint
Common Mistakes
Using PDO::FETCH_OBJ returns an object, not an array.
2fill in blank
medium

Complete the code to fetch all rows as objects using PDO.

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

Fix the error in the code to fetch a numeric array from the database.

PHP
<?php
$stmt = $pdo->query('SELECT id, price FROM items');
$row = $stmt->fetch([1]);
echo $row[0] . ' costs ' . $row[1];
?>
Drag options to blanks, or click blank then click option'
APDO::FETCH_BOTH
BPDO::FETCH_OBJ
CPDO::FETCH_ASSOC
DPDO::FETCH_NUM
Attempts:
3 left
💡 Hint
Common Mistakes
Using PDO::FETCH_ASSOC causes $row[0] to be undefined.
4fill in blank
hard

Fill both blanks to fetch rows as both numeric and associative arrays.

PHP
<?php
$stmt = $pdo->query('SELECT username, email FROM members');
$row = $stmt->fetch([1] | [2]);
print_r($row);
?>
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 PDO::FETCH_OBJ does not provide array keys.
5fill in blank
hard

Fill all three blanks to fetch rows as objects and access a property.

PHP
<?php
$stmt = $pdo->query('SELECT id, title FROM books');
$rows = $stmt->fetchAll([1]);
foreach ($rows as [2]) {
    echo [3]->title . "\n";
}
?>
Drag options to blanks, or click blank then click option'
APDO::FETCH_ASSOC
B$book
C$b
DPDO::FETCH_OBJ
Attempts:
3 left
💡 Hint
Common Mistakes
Using PDO::FETCH_ASSOC returns arrays, so ->title would cause error.