Think of a paper form at a bank. The fields are already printed ("Name:", "Amount:"), and you may only fill in the blanks. Whatever you write in a blank is still treated as an answer, not as a new instruction for the clerk. A parameterized query (often called a prepared statement) works like that form: the structure of the query is the part printed first, and user input only fills in the blanks. So the input can't become part of the SQL command.
In the previous lesson you saw how SQL injection works. Now there is one focus: how to write a query that can't be injected. One technique solves almost every case.
The problem: query and data mixed together
A vulnerable query joins (concatenates) user input straight into the text of the query, then runs it with db.exec:
// VULNERABLE: input concatenated into the query text
const q = "SELECT * FROM users WHERE username = '" + input + "'";
db.exec(q);
If input holds an ordinary name like budi, the query becomes ... WHERE username = 'budi'. The result is correct. But if input holds ' OR '1'='1, the text of the query changes into:
SELECT * FROM users WHERE username = '' OR '1'='1'
What happens:
- The quote at the start of the input closes the
usernamestring early. - The rest,
OR '1'='1', is now part of the SQL, not data.'1'='1'is always true, so WHERE matches every row. - The result: the whole
userstable comes back,admin,budiandsiti. Only one name was asked for.
The root cause: the input turned into code because it was mixed into the text of the query.
Parameterized query: separate the query from the data
The fix has two steps:
- Write the query with a placeholder (a
?or:name) where the data goes. - Send the value separately.
The database driver (the library that connects your code to the database) then matches each value to its placeholder. The value you send is always treated as one whole piece of data, never as SQL.
// SAFE: ? is a placeholder, the input is sent separately
db.exec("SELECT * FROM users WHERE username = ?", [input]);
Now send the input ' OR '1'='1 again. Before you read on, guess: does the query leak and return every user, or does it find nobody?
The query stays SELECT * FROM users WHERE username = ?. The database looks for a user whose username is exactly the text ' OR '1'='1, quotes and spaces included. No user has that name, so the result is 0 rows.
In PHP with PDO, a placeholder can also have a name, like :username, and the query is prepared first with prepare():
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->execute([":username" => $username]);
prepare()sends the structure of the query to the database first, before any data arrives. At that point the database already knows which part is the query and which part is data.execute([...])sends the value as pure data. Whatever it contains, that value is only compared as text.
ORM: safe by default
An ORM is a library that lets you write queries with methods instead of SQL text. Eloquent (Laravel) and Prisma are examples. Inside, an ORM uses parameter binding automatically, which means it sends values separately, like ?:
// Eloquent: where() binds the value separately on its own
$user = User::where('username', $username)->first();
where('username', $username) is safe from SQL injection, because $username is sent as data. You don't have to think about quotes at all, or about escaping: adding a special mark in front of a quote, so the quote is read as plain text.
Type validation as an extra layer
If an input must be a number, check it before you use it:
$id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
if ($id === false) {
http_response_code(400);
exit("Invalid ID");
}
Validation does not replace a parameterized query. It is an extra layer: input with a clearly wrong shape is refused early.
⚠️ "Safe" shortcuts that still leak
- Relying only on escaping. If you escape one place at a time, it is easy to miss one place, and one is enough for an attack. A parameterized query doesn't need that step.
- Blacklisting characters. There is always a way around blocking words like
ORor--. The right way: separate the query from the data, don't guess harmful input. raw()or interpolation in an ORM.DB::select("... role = '$role'")joins$rolestraight into the text of the query. That query is vulnerable again, even though you use Laravel. WriteDB::select("... role = ?", [$role])with parameter binding.- Table or column names from input. A placeholder is only for values, not for table or column names. If a name must come from input, match it against a list of allowed names (a whitelist).
TL;DR: SQL injection is prevented by separating the query from the data. Don't join input into the text of a query. Use a ? or :name placeholder, then send the value separately through prepare() and execute(). The input ' OR '1'='1 is then searched for as text exactly as typed, is not found, and returns 0 rows instead of leaking every row. An ORM (a library for writing queries with methods) like Eloquent (where('username', $username)) is safe by default because it sends values separately on its own. Escaping (marking quotes one by one) and blacklisting are not enough. Type validation is only an extra layer.
⚡ Query and data mixed together
Write:
const q = "SELECT * FROM users WHERE username = '" + input + "'";
db.exec(q);
Meaning: input is joined into the text of the query, and db.exec runs it. The input ' OR '1'='1 closes the string early. The rest becomes a piece of SQL that is always true, so every row of users comes back.
⚡ A placeholder, the value sent separately
Write:
db.exec("SELECT * FROM users WHERE username = ?", [input]);
Guess first: the input ' OR '1'='1 is sent again. Does everything leak, or is nobody found?
Nobody is found, 0 rows. The database looks for a username that is exactly that text.
Meaning: A value that goes through a placeholder is always treated as one whole piece of data, never as SQL. In PDO, call prepare() first, then execute().
⚡ An ORM is safe by default
Write:
$user = User::where('username', $username)->first();
Meaning: Eloquent, an ORM (a library for writing queries with methods), sends the value separately on its own, the same as ?.
⚡ Shortcuts that still leak
Guess first: what is wrong with DB::select("... role = '$role'") in Laravel?
The variable is joined straight into the text of the query, so it is vulnerable again. Write DB::select("... role = ?", [$role]).
Meaning: Escaping (marking quotes one by one) and blacklisting are not enough. Type validation is only an extra layer, not a replacement for placeholders.