php · level 2 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
One fetch, then a fetchAll. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$db = new PDO("sqlite::memory:");
$db->exec("CREATE TABLE films (title TEXT, year INTEGER)");
$db->exec("INSERT INTO films VALUES ('Up', 2009), ('Coco', 2017), ('Soul', 2020)");
$result = $db->query("SELECT title FROM films WHERE year < 2018 ORDER BY title");
$first = $result->fetch(PDO::FETCH_ASSOC);
echo $first["title"] . "\n";
echo count($result->fetchAll(PDO::FETCH_ASSOC)) . " more\n";
your turn
Your turn. Set the cut for the next round.
Type the lowest score that gets through to the next round, as a whole number. Run it to see who made it, best first.
fix it
Both users should be listed, but it crashes. Fix it.
fetchhands back one row, Mo's. So what is the loop walking through on line 6?- The loop visits Mo's name and town as plain strings, which have no keys. You want every row.
- Change
fetchtofetchAllon line 5, then press run.
nailed it
you can ask a database anything. :D
SELECT ... FROM ... WHERE ... ORDER BYpicks rows.fetchAllgives every row as an array of records.fetchgives one row, orfalsewhen none are left.
new words in your collection
- query
- fetchAll
- fetch
This lesson isn’t saved. A free account remembers every lesson you finish.