Prevent SQL injection in PHP with prepared statements
SQL injection is what happens when user input becomes part of your SQL command. PHP's own manual gives you the definitive fix: prepared statements, where parameters never need manual quoting because the driver handles them. This guide shows the pattern in both PDO and MySQLi, from php.net.
Why prepared statements work
From the PDO manual: a prepared statement is a compiled template for your SQL, customized with variable parameters. Two benefits: the query is parsed and optimized once even when executed many times, and parameters do not need to be quoted, since the driver handles that automatically. The manual's promise is direct: if your application exclusively uses prepared statements, you can be sure no SQL injection will occur, with the caveat that other parts of the query built from unescaped input are still injectable.
PDO with named placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();
The value goes in as a parameter at execute time, never concatenated into the SQL string.
Bonus: run one statement many times
The manual's first example inserts many rows with one prepared INSERT and named placeholders, binding fresh values per execution:
$stmt = $pdo->prepare('INSERT INTO registry (name, value) VALUES (:name, :value)');
$stmt->execute(['name' => 'one', 'value' => 1]);
$stmt->execute(['name' => 'two', 'value' => 2]);
Same statement, prepared once, executed with different parameters: faster and safe at the same time.
MySQLi with positional placeholders
The MySQLi quickstart describes the same idea: a parameterized statement executes efficiently and protects against SQL injections:
$stmt = $mysqli->prepare('SELECT * FROM users WHERE email = ?');
$stmt->bind_param('s', $email);
$stmt->execute();
What still bites you
- Dynamic identifiers: table and column names cannot be parameters. Whitelist them in code instead of interpolating input.
- Partial adoption: one concatenated query in an otherwise prepared codebase is still a hole. The manual's guarantee is for exclusive use.
- LIKE values and IN lists: these need their parameter pattern handled deliberately; do not fall back to string building when they get awkward.
A quick audit you can do today
Search your codebase for query calls whose arguments contain $_GET, $_POST, $_REQUEST or $_COOKIE interpolated into strings. Every hit is either a bug or a place to convert to a prepared statement.
Related: PHP cURL HTTP POST example for safe outbound requests, and MySQL error 1045 when the database itself refuses your login.
