php · level 2 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Prices are going up. 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 prices (id INTEGER PRIMARY KEY, item TEXT, pence INTEGER)");
$db->exec("INSERT INTO prices (item, pence) VALUES ('tea', 150), ('cake', 250), ('scone', 200)");
$rise = $db->prepare("UPDATE prices SET pence = pence + 10 WHERE pence >= ?");
$rise->execute([200]);
echo $rise->rowCount() . " prices went up\n";
your turn
Your turn. Clear out a plant.
Type the ID of the plant to remove: 1 is the fern, 2 the cactus, 3 the ivy. Then try 9 and see what changes.
fix it
Only Amy wanted a new name. Can you fix it?
- Every pupil is now called Amelia. Which part of an
UPDATEpicks the rows to change? - Add a
WHEREthat points at Amy's ID, which is 1, and send the ID as a second value. - Use
UPDATE pupils SET name = ? WHERE id = ?andexecute(["Amelia", 1]), then press run.
nailed it
you change exactly the rows you mean. :D
id INTEGER PRIMARY KEYgives every row its own ID.UPDATEandDELETEneed aWHERE, or every row changes.rowCounttells you how many rows changed.
new words in your collection
- primary key
- lastInsertId
- rowCount
This lesson isn’t saved. A free account remembers every lesson you finish.