×

php · level 2 · unit 6 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Ask the database exactly the question you want answered.

A is a question for the database. SELECT name, age FROM pets WHERE age > 2 ORDER BY age DESC reads almost like English: these columns, from this table, only rows that match, biggest age first. Without DESC, ORDER BY goes smallest first.

collects every row of the answer into an array of records, like the nested arrays in unit 1. PDO::FETCH_ASSOC is a constant that belongs to PDO, reached with ::. It asks for rows with keys.

hands you one row at a time, and false when none are left. It suits questions with one answer, like a count.

<?php
$db = new PDO("sqlite::memory:");
$db->exec("CREATE TABLE pets (name TEXT, age INTEGER)");
$db->exec("INSERT INTO pets VALUES ('Rex', 3), ('Tilly', 5), ('Pip', 1)");
$rows = $db->query("SELECT name, age FROM pets WHERE age > 2 ORDER BY age DESC")->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $pet) {
    echo "{$pet["name"]}: {$pet["age"]}\n";
}
$count = $db->query("SELECT COUNT(*) AS total FROM pets")->fetch(PDO::FETCH_ASSOC);
echo "{$count["total"]} pets in all\n";

COUNT(*) counts rows, and AS total gives that answer a key you can use.