×

php · level 2 · unit 6 · lesson 1

  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

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.