Lesson 2 of 9 · 24m
SQL Injection: Prepared Statements and Query Discipline
Parameterized queries are the baseline; the real discipline is knowing what placeholders cannot do and designing queries so untrusted data never becomes SQL syntax.
Every senior PHP developer has met the same ghost: a search form concatenated into SQL in 2007, copied into a reporting page in 2012, and still reachable from an employee-only URL nobody remembers. SQL injection survives because it is usually not one mistake — it is a style of programming where strings cross trust boundaries without changing shape.
Placeholders separate code from data
With PDO, the fix is boring and non-negotiable:
$pdo = new PDO('mysql:host=127.0.0.1;dbname=app;charset=utf8mb4', 'app_user', $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
]);
$stmt = $pdo->prepare('SELECT id, email FROM users WHERE email = :email LIMIT 1');
$stmt->execute(['email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);The database receives the structure of the query and the values separately. The value can contain quotes, semicolons, or the text DROP TABLE; it remains data. That is the entire point.
What placeholders cannot parameterize
Placeholders bind values, not syntax. You cannot bind a table name, column name, sort direction, or SQL keyword. Those require allowlists.
$columns = ['email' => 'email', 'created' => 'created_at'];
$column = $columns[$sortKey] ?? 'created_at';
$direction = $directionKey === 'desc' ? 'DESC' : 'ASC';
$sql = "SELECT id, email FROM users ORDER BY {$column} {$direction} LIMIT 50";The IN-list and integer traps
You cannot bind one placeholder to a list. Generate one placeholder per value after validating the values as integers:
$ids = array_filter(array_map('intval', (array) ($_POST['ids'] ?? [])));
if ($ids === []) {
throw new InvalidArgumentException('No valid ids');
}
$marks = implode(',', array_fill(0, count($ids), '?'));
$stmt = $pdo->prepare("SELECT id, name FROM teams WHERE id IN ({$marks})");
$stmt->execute(array_values($ids));LIMIT and OFFSET are another classic emulation failure. Validate them as integers and interpolate integers, not raw request strings.
Second-order injection is still injection
A stored value can become dangerous when later concatenated into a different query, report, export, or shell command. Do not say "it came from our database, so it is trusted." Escaping has the same problem as concatenation: it depends on perfect manual use everywhere. Parameterization is architectural separation.
Least privilege makes mistakes smaller
The application database user usually does not need DROP, FILE, SUPER, or schema-alter rights in production. Separate migration credentials from runtime credentials. When injection still happens — because someday something will slip through — least privilege determines whether the attacker reads one table or owns the server.
Field notes
- Turn off emulated prepares for PDO MySQL unless you have proven a specific driver constraint; native prepares expose mistakes earlier.
addslashes()is not SQL escaping. It does not know the connection encoding and has no place in new code.- ORM query builders are safe only when raw expressions are treated as dangerous machinery. One
whereRaw()can undo the model layer. - Log abuse signals, but never passwords, tokens, or personal data.
Was this lesson helpful?