SQL injection defense
PHP hands values to the database separately from the SQL text, and that one habit closes the biggest hole in web code. The examples below run on SQLite in memory, so the injection attempt and its harmless result are both real.
How injection reads
Injection happens when user input is glued into SQL text and the database reads part of that input as code. A quote in a name can then change the shape of the query.
The defense is structural and never relies on blocking bad words. Keep data and SQL text apart so input can only ever be a value.
<?php $pdo = new PDO("sqlite::memory:"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT)"); $pdo->exec("INSERT INTO users (email) VALUES ('ada@example.com'), ('bob@example.com')"); foreach (["ada@example.com", "' OR 1=1 --"] as $email) { $stmt = $pdo->prepare("SELECT id FROM users WHERE email = :email"); $stmt->execute([":email" => $email]); echo $email, ": ", count($stmt->fetchAll()), PHP_EOL; }
php attack.php
ada@example.com: 1
' OR 1=1 --: 0
The injection string finds nothing, because it never leaves its place as a value. The count comes from the rows the statement fetched: on SQLite rowCount() reports zero for a SELECT, so this page counts the rows itself.
Prepare everything
Prepared statements send the SQL shape first and the values separately. The database compiles the query before it ever sees user data.
Use named placeholders for every value that comes from outside. Never build SQL by joining input with dots.
<?php $pdo = new PDO("sqlite::memory:"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec("CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT, body TEXT)"); $title = "Hello"; $body = "World"; $stmt = $pdo->prepare("INSERT INTO posts (title, body) VALUES (:title, :body)"); $stmt->execute([":title" => $title, ":body" => $body]); echo $pdo->lastInsertId(), PHP_EOL;
php prepare.php
1
The new row carries the first id of the table, and the values arrived through the placeholders rather than inside the SQL string. An apostrophe in the title would be data here, not syntax.
LIKE wildcards safely
Search boxes often need partial matches with percent and underscore wildcards. Build the pattern in PHP and send it as one bound value.
The placeholder still carries the whole pattern. User text inside it can never escape into SQL syntax.
<?php $pdo = new PDO("sqlite::memory:"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec("CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT)"); $pdo->exec("INSERT INTO posts (title) VALUES ('Hello world'), ('Help me'), ('Goodbye')"); $q = "Hel"; $term = "%" . $q . "%"; $stmt = $pdo->prepare("SELECT id FROM posts WHERE title LIKE :term"); $stmt->execute([":term" => $term]); echo count($stmt->fetchAll()), PHP_EOL;
php like.php
2
Two titles start with the three letters, and the pattern reached the database as one value with its percent signs inside it.
LIMIT with ints
Limits and offsets cannot always be bound as placeholders, so force them to integers in PHP. Casting drops everything except digits and sign.
Clamp the result to a sane range before it reaches SQL. The query then contains only digits built by your own code.
<?php $pdo = new PDO("sqlite::memory:"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec("CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT)"); $pdo->exec("INSERT INTO posts (title) VALUES ('a'), ('b'), ('c')"); $n = "3abc"; $limit = max(1, (int) $n); $sql = sprintf("SELECT id FROM posts LIMIT %d", $limit); $stmt = $pdo->query($sql); echo $limit, PHP_EOL; echo count($stmt->fetchAll()), PHP_EOL;
php limit.php
3
3
The cast keeps the digits and throws the rest away, so the statement asks for three rows and gets three. A value with no digits at all becomes zero, which the max() lifts to one.
Exercises
- Add a third user and run the attack example again.
- Send "a' OR '1'='1" as the LIKE term and explain the count.
- Escape a percent sign in a search term with str_replace("%", "\%", $q) and check the count.
- Pass -5 as the limit and read which limit the clamped query uses.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a prepared statement keep apart?
Answer
The SQL text and the values
The database compiles the statement first, so a value can never be read as a part of the query.
-
Why is a bound value safe where a glued string is not?
Answer
The value is sent as data, never parsed as SQL
The placeholder marks one value slot, so quotes and keywords inside the value stay inside it.
-
How is a LIKE search built safely?
Answer
Build the pattern with percent signs in PHP and bind the whole pattern
The pattern is one value, so the wildcards travel with it and the user text cannot reach the syntax.
-
Why does the LIMIT example cast the value to an integer?
Answer
A placeholder in LIMIT is not accepted by every driver, and a cast fixes the type
Some drivers refuse a bound LIMIT, so the number is built by PHP and the cast proves it is only digits.
-
What does this program print?
<?php $pdo = new PDO("sqlite::memory:"); $pdo->exec("CREATE TABLE users (email TEXT)"); $pdo->exec("INSERT INTO users (email) VALUES ('ada@example.com')"); $email = "' OR 1=1 --"; $stmt = $pdo->prepare("SELECT email FROM users WHERE email = :email"); $stmt->execute([":email" => $email]); echo count($stmt->fetchAll());Answer
0
The whole string is compared as one email value, and no row carries it.
-
What does this program print?
<?php $pdo = new PDO("sqlite::memory:"); $pdo->exec("CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT)"); $stmt = $pdo->prepare("INSERT INTO posts (title) VALUES (:title)"); $stmt->execute([":title" => "One"]); echo $pdo->lastInsertId();Answer
1
The row is the first in the table, so SQLite gives it the id 1.
-
What does this program print?
<?php $pdo = new PDO("sqlite::memory:"); $pdo->exec("CREATE TABLE posts (title TEXT)"); $pdo->exec("INSERT INTO posts (title) VALUES ('Hello'), ('Help'), ('Goodbye')"); $term = "%" . "Hel" . "%"; $stmt = $pdo->prepare("SELECT title FROM posts WHERE title LIKE :term"); $stmt->execute([":term" => $term]); echo count($stmt->fetchAll());Answer
2
Two titles contain the three letters, and the third one does not.
-
What does this program print?
<?php $n = "3abc"; echo (int) $n, " ", max(1, (int) "abc");Answer
3 1
The cast takes the leading digits, and a string without digits becomes zero, which
max()lifts to one. -
Why is
PDO::quote()not enough around a value?Answer
It is easy to forget a call, and the quoting rules differ between drivers
One missed concatenation reopens the hole, while a placeholder needs no remembering at the value site.
-
A search term is bound to a LIKE pattern. Which input still changes the meaning of the search?
Answer
A percent sign, which becomes a wildcard
The percent sign is the wildcard of LIKE, so it widens the match; it is data, not injection, but the result may surprise.
The examples call sprintf() and max(). The programs on this page were run with PHP 8.5.13 (php -v) on SQLite in memory, with the commands shown above.
Article author: Arthur Isaev