×

php · level 2 · unit 6 · lesson 4

  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

Give every row an ID, then change the rows you mean.

To change one row, you need a way to point at it. Make a column and SQLite numbers each new row for you: 1, 2, 3. A primary key never repeats. After an insert, tells you the ID it chose.

UPDATE tasks SET done = 1 WHERE id = ? changes rows, and DELETE FROM tasks WHERE id = ? removes them. The WHERE picks which ones. Forget it and every row in the table changes.

After execute, tells you how many rows were changed, which makes a handy check.

<?php
$db = new PDO("sqlite::memory:");
$db->exec("CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT, done INTEGER)");
$add = $db->prepare("INSERT INTO tasks (title, done) VALUES (?, 0)");
$add->execute(["Walk the dog"]);
$add->execute(["Bake bread"]);
echo "Bake bread got ID " . $db->lastInsertId() . "\n";
$tick = $db->prepare("UPDATE tasks SET done = 1 WHERE id = ?");
$tick->execute([1]);
echo $tick->rowCount() . " task ticked off\n";
echo $db->exec("DELETE FROM tasks WHERE done = 1") . " task deleted\n";

exec also gives back how many rows it changed, as the last line shows.