×

php · level 2 · unit 6 · lesson 3

  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

Placeholders keep visitors' text out of your SQL.

Never glue a visitor's text into SQL. A name like Bob'; DROP TABLE users would end your text early at the quote, and the rest would run as SQL. That is , one of the most common attacks on websites.

Instead, the SQL with a , ?, wherever a value goes: $db->prepare("INSERT INTO users (name) VALUES (?)"). Then execute([$name]) sends the values separately, in order. The database treats them as plain data, never as commands.

prepare gives back an object of its own. Call execute on it as often as you like, then fetch or fetchAll after a SELECT.

<?php
$db = new PDO("sqlite::memory:");
$db->exec("CREATE TABLE users (name TEXT, town TEXT)");
$add = $db->prepare("INSERT INTO users (name, town) VALUES (?, ?)");
$add->execute(["Ana", "Leeds"]);
$add->execute(["Bob'; DROP TABLE users", "Hull"]);
$find = $db->prepare("SELECT name FROM users WHERE town = ?");
$find->execute(["Hull"]);
echo $find->fetch(PDO::FETCH_ASSOC)["name"] . "\n";

Placeholders take values only, so table and column names are always written into the SQL by you.