SQL Injection and Parameterized Queries
Follow a product search into SQL, then keep the query structure separate from the values supplied by a customer.
You’re reading a preview. Premium includes the full lesson and specialist practice. View the full curriculum.
A customer searches a shop for a green mug. The server puts the search text into a database query and returns matching products. That is the ordinary case to keep working.
Now imagine the search text can end a quoted value and add a new SQL condition. The customer is no longer just choosing a product name; they are changing the database's instructions. That is SQL injection.
We'll compare the complete query before and after the change, then keep the SQL structure fixed and pass the search text separately. Those separately supplied values are bound parameters. The shop restriction must keep working too.
Separate the SQL statement from its values
Read the final execution call, then walk backward through every fragment that contributes to its first argument. A query assembled across helpers can hide an unsafe segment behind an innocent variable name. Escaping performed for HTML, URLs, JSON, or a different database is not proof of SQL safety.
// Unsafe teaching example: both occurrences become SQL source.
const q = req.query.q;
const statement =
'SELECT id, name, price FROM products ' +
'WHERE shop_id = ' +
trustedShopNumber +
" AND (name LIKE '%" +
q +
"%' OR description LIKE '%" +
q +
"%')";
const rows = await connection.query(statement);
Even a trusted shop number does not protect the search fragments. An attacker-controlled quote can end the intended string literal; operators, parentheses, or comments may then affect the remaining expression. Work through the actual SQL dialect and grouping. Do not assume every familiar payload fits every query.
Follow the same input through parsing, construction, and execution.
Parse. Require one bounded scalar before building a search pattern.
if (typeof q !== "string") throw badRequest();
if (q.length > 120) throw badRequest();
const pattern = "%" + q + "%";
Construct. The statement contains placeholders in both value positions.
SELECT id, name
FROM products
WHERE shop_id = ?
AND (name LIKE ? OR description LIKE ?)
LIMIT 50;
Execute. Use the documented driver binding API with the verified tenant and both patterns.
await connection.execute(statement, [
verifiedShopId,
pattern,
pattern,
]);
Review question: A value stays data only when its final use preserves that role.