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?
$stmt = $pdo->query('SELECT id, name FROM users ORDER BY id LIMIT 1'); $row = $stmt->fetch(PDO::FETCH_ASSOC); print_r($row);
fetch() returns one row as an associative array if you use PDO::FETCH_ASSOC.
The fetch() method returns the next row from the result set. Using PDO::FETCH_ASSOC returns an associative array with column names as keys.
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?
$stmt = $pdo->query('SELECT id, name FROM users'); $rows = $stmt->fetchAll(PDO::FETCH_NUM); print_r($rows);
PDO::FETCH_NUM returns numeric keys for columns.
fetchAll(PDO::FETCH_NUM) returns an array of rows, each row is an indexed array with numeric keys.
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?
$stmt = $pdo->query('SELECT id, name FROM users'); $row = $stmt->fetchAll(PDO::FETCH_ASSOC); print_r($row[0]['nonexistent_column']);
Accessing an array key that does not exist triggers a notice.
fetchAll(PDO::FETCH_ASSOC) returns an array of associative arrays. Accessing a missing key triggers an undefined index notice.
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?
$stmt = $pdo->query('SELECT id, name FROM users ORDER BY id LIMIT 1'); $user = $stmt->fetch(PDO::FETCH_OBJ); echo $user->name;
PDO::FETCH_OBJ returns an object with properties matching column names.
fetch(PDO::FETCH_OBJ) returns an object. Accessing $user->name prints the user's name.
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);fetchAll() returns all rows as an array of arrays.
fetchAll(PDO::FETCH_ASSOC) returns an array with one element per row. Since the table has 5 rows, count() returns 5.