php · level 2 · unit 6 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A stores data in tables, and talks to it.
Files suit notes, but finding one entry among thousands gets slow and messy. A database keeps data in tables: rows and columns, like a spreadsheet. You talk to it in SQL, a language of its own, written inside PHP strings.
PHP's toolkit for databases is called PDO. new PDO("sqlite::memory:") makes an : a value that bundles data with its own functions, called methods. This one is a link to a fresh SQLite database, a small kind of database kept inside your program while it runs. Call a with ->.
$db->exec(...) runs SQL that changes things, like CREATE TABLE and INSERT INTO. $db->query("SELECT ...") asks for data, and foreach hands you each row as an array.
<?php
$db = new PDO("sqlite::memory:");
$db->exec("CREATE TABLE pets (name TEXT, age INTEGER)");
$db->exec("INSERT INTO pets (name, age) VALUES ('Rex', 3), ('Tilly', 5)");
foreach ($db->query("SELECT name, age FROM pets") as $pet) {
echo "{$pet["name"]} is {$pet["age"]}\n";
} In SQL, text goes in single quotes, like 'Rex', so it sits happily inside PHP's double quotes.
guess first
Two snacks go in. What comes out?
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 snacks (name TEXT, price INTEGER)");
$db->exec("INSERT INTO snacks (name, price) VALUES ('crisps', 80)");
$db->exec("INSERT INTO snacks (name, price) VALUES ('flapjack', 120)");
foreach ($db->query("SELECT name FROM snacks") as $snack) {
echo $snack["name"] . "\n";
}
your turn
Your turn. Start a library.
Type a book title and its author inside the single quotes, without any apostrophes. Then run it.
fix it
Biscuit is in the table, but the query fails. Fix it.
- Read the PDOException:
no such table. Which table is line 5 asking for? - Compare the table name in
CREATE TABLEwith the one afterFROM. - The table is called pets. Change
FROM pettoFROM pets, then press run.
nailed it
you built your first database. :D
- A database keeps data in tables of rows and columns.
new PDO(...)makes a database object, and->calls its methods.execchanges data,queryreads it back.
new words in your collection
- database
- SQL
- object
- method
This lesson isn’t saved. A free account remembers every lesson you finish.