Challenge 2 — Solution
Task: Assuming a "products" table with columns id, name, and price,
write prepared statements (with placeholders) for: inserting a new
product, selecting all products with a price above a given value, and
updating a specific product's price by id.
prepare("INSERT INTO products (name, price) VALUES (:name, :price)");
$stmt->execute(['name' => "Wireless Mouse", 'price' => 19.99]);
echo "New product ID: " . $pdo->lastInsertId() . "
";
// Select all products above a given price
$stmt = $pdo->prepare("SELECT * FROM products WHERE price > :minPrice");
$stmt->execute(['minPrice' => 15]);
$expensiveProducts = $stmt->fetchAll();
foreach ($expensiveProducts as $product) {
echo $product['name'] . " - £" . $product['price'] . "
";
}
// Update a specific product's price by id
$stmt = $pdo->prepare("UPDATE products SET price = :newPrice WHERE id = :id");
$stmt->execute(['newPrice' => 17.50, 'id' => 1]);
?>
Output:
New product ID: 1
Wireless Mouse - £19.99
Notes:
- All three statements use named placeholders (:name, :minPrice, :id,
etc.) rather than concatenating any value directly into the SQL
text - exactly the SQL-injection-safe pattern from the chapter,
applied to a realistic products table.
- lastInsertId() retrieves the auto-increment id PHP just generated for
the newly inserted row, without needing a separate SELECT to look it
up.
- The UPDATE statement includes a WHERE id = :id clause deliberately -
omitting it would set every single row's price to 17.50, exactly the
mistake the chapter's own warn-box calls out.