Lukas' Notes

web security databases

Definition

Prepared Statement

A prepared statement is the canonical defence against SQL injection. The application sends a query template with placeholder parameters to the database; the database compiles the query (treating it as code) once; the application then supplies only the parameter values (data), which the database substitutes without re-parsing. Code and data keep separate roles, so a ' in a parameter can never become SQL syntax.

<?php
$query = "SELECT * FROM users WHERE user = ? AND password = ?";
$sth = $db->prepare($query);
$sth->bindValue(1, $_POST["user"]);
$sth->bindValue(2, $_POST["password"]);
$sth->execute();
?>

Shortcomings

Shortcomings

  • Emulated prepared statements bind parameters client-side and can be bypassed (e.g. CVE-2024-36039).
  • Some drivers offer only partial support — e.g. no placeholder for a table name, which forces concatenation back into the query and reintroduces the injection surface.