Complete the code to fetch a row as an associative array using PDO.
<?php $stmt = $pdo->query('SELECT * FROM users'); $row = $stmt->fetch([1]); print_r($row); ?>
PDO::FETCH_ASSOC fetches the row as an associative array with column names as keys.
Complete the code to fetch all rows as objects using PDO.
<?php $stmt = $pdo->query('SELECT * FROM products'); $rows = $stmt->fetchAll([1]); foreach ($rows as $product) { echo $product->name . "\n"; } ?>
PDO::FETCH_OBJ fetches rows as objects, allowing property access like $product->name.
Fix the error in the code to fetch a numeric array from the database.
<?php $stmt = $pdo->query('SELECT id, price FROM items'); $row = $stmt->fetch([1]); echo $row[0] . ' costs ' . $row[1]; ?>
PDO::FETCH_NUM fetches the row as a numeric array, so $row[0] and $row[1] work correctly.
Fill both blanks to fetch rows as both numeric and associative arrays.
<?php $stmt = $pdo->query('SELECT username, email FROM members'); $row = $stmt->fetch([1] | [2]); print_r($row); ?>
Combining PDO::FETCH_ASSOC and PDO::FETCH_NUM fetches both keys and numeric indexes, same as PDO::FETCH_BOTH.
Fill all three blanks to fetch rows as objects and access a property.
<?php $stmt = $pdo->query('SELECT id, title FROM books'); $rows = $stmt->fetchAll([1]); foreach ($rows as [2]) { echo [3]->title . "\n"; } ?>
PDO::FETCH_OBJ fetches rows as objects. Using $book as the loop variable allows accessing $book->title.