SQL Injection: Why You Never Build Queries from Text
See a real SQL injection attack succeed against a query built with string formatting, then stop it with parameterised queries and an allow-list, and verify the damage with an independent count.
In this lesson you will
- Explain how SQL injection works
- Reproduce a login bypass and a data leak
- Use parameterised queries
- Use an allow-list for names that cannot be parameters
About 28 minutes
The member who typed a quote
Kofi’s first version of the login check built its query by pasting the member’s input into the SQL text. It worked for every normal member, until someone typed a single quote followed by OR 1=1. SQL injection happens when untrusted input becomes part of the SQL command instead of staying data. The database cannot tell which part of the text the programmer wrote and which part the attacker wrote, so the attacker can change the meaning of the query: skip a password check, read other tables, or alter data. It has been one of the most common and most damaging web vulnerabilities for more than twenty years, and it is completely preventable.
The cure is simple and has no exceptions: never build SQL by joining strings with values. Use a parameterised query, also called a prepared statement, where the SQL text has placeholders and the values are sent separately. The database parses the command first, with the placeholders, and only then plugs the values in as pure data, so a quote in a value is just a character. Parameters work for values only. Table and column names cannot be parameters, so if a user can choose a sort column, you check it against a fixed list of allowed names, an allow-list, and never insert the user’s text.
import sqlite3, json
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE members (id INTEGER PRIMARY KEY, name TEXT, password TEXT, is_admin INTEGER);
CREATE TABLE secrets (id INTEGER PRIMARY KEY, note TEXT);
INSERT INTO members VALUES (1, 'ama', 'pw-ama', 0), (2, 'ben', 'pw-ben', 0), (3, 'kofi', 'pw-kofi', 1);
INSERT INTO secrets VALUES (1, 'alarm code 4812');
""")
total_members = db.execute("SELECT COUNT(*) FROM members").fetchone()[0]
def login_bad(name, password):
sql = "SELECT id, name FROM members WHERE name = '" + name + "' AND password = '" + password + "'"
try:
return sql, db.execute(sql).fetchall()
except sqlite3.Error as e:
return sql, "error: " + str(e)
def login_good(name, password):
return db.execute("SELECT id, name FROM members WHERE name = ? AND password = ?", (name, password)).fetchall()
attacks = {
"normal": ("ama", "pw-ama"),
"wrong password": ("ama", "guess"),
"bypass": ("ama' --", "anything"),
"match everyone": ("x' OR '1'='1", "x' OR '1'='1"),
"leak another table": ("x' UNION SELECT id, note FROM secrets --", "z"),
"break the syntax": ("o'brien", "pw"),
}
report = {}
for label, (n, p) in attacks.items():
sql, rows = login_bad(n, p)
good = login_good(n, p)
report[label] = {"bad": rows, "good": good}
print(label.ljust(20), "| unsafe ->", rows, "| parameterised ->", good)
print("unsafe query text for the bypass:", login_bad("ama' --", "anything")[0])
ORDER_COLUMNS = {"name", "id"}
def list_members(sort):
if sort not in ORDER_COLUMNS: raise ValueError("bad sort column")
return [r[0] for r in db.execute("SELECT name FROM members ORDER BY " + sort)]
try:
list_members("name; DROP TABLE members")
except ValueError as e:
print("allow-list rejected the sort column:", e, "| still", db.execute("SELECT COUNT(*) FROM members").fetchone()[0], "members")
print("sorted by name:", list_members("name"))
print("DATA " + json.dumps({"report": report, "total": total_members}))
normal | unsafe -> [(1, 'ama')] | parameterised -> [(1, 'ama')]
wrong password | unsafe -> [] | parameterised -> []
bypass | unsafe -> [(1, 'ama')] | parameterised -> []
match everyone | unsafe -> [(1, 'ama'), (2, 'ben'), (3, 'kofi')] | parameterised -> []
leak another table | unsafe -> [(1, 'alarm code 4812')] | parameterised -> []
break the syntax | unsafe -> error: near "brien": syntax error | parameterised -> []
unsafe query text for the bypass: SELECT id, name FROM members WHERE name = 'ama' --' AND password = 'anything'
allow-list rejected the sort column: bad sort column | still 3 members
sorted by name: ['ama', 'ben', 'kofi']
The table shows the same six inputs sent to two versions of the login. A normal login works in both, and a wrong password fails in both. Then the attacks begin. The input ama’ — turns the rest of the query into an SQL comment, so the password check disappears: the unsafe version logs in as Ama with a password of “anything”, and the parameterised version finds no member with that strange name and refuses. The input x’ OR ‘1’=’1 makes the condition true for every row, so the unsafe query returned all 3 members, including the administrator. The input with UNION SELECT glued a second query onto the first, and the unsafe version returned a row from another table, [1, “alarm code 4812”], a secret that has nothing to do with logins. Even the innocent name o’brien broke the unsafe query with a syntax error, which shows that this bug hurts honest users too, and that an error message can reveal the structure of the database.
The parameterised version returned an empty list for every attack, because the whole input is compared as a name. For parts of a query that cannot be parameters, such as the column in ORDER BY, the allow-list accepted “name” and rejected “name; DROP TABLE members” before it reached the database, and the table still has its three members. Defence in depth adds more layers: give the database account only the rights it needs, hash passwords instead of storing them, which lesson 6 shows, and do not show database errors to users.
Independent check: the number of rows in the members table was counted before any attack, 3, and it matches the number of rows that the match-everyone attack returned, so the attack really did match every row, and no row was added or removed by the tests: the count after the rejected DROP attempt is the same. A parameterised query was also tested with every attack string and returned nothing for all four malicious inputs.
Check by hand: with the input ama’ — the query text becomes SELECT … WHERE name = ‘ama’ — ‘ AND password = ‘anything’, and everything after the two dashes is a comment, so the condition is only name = ‘ama’. With the OR input, name = ‘x’ OR ‘1’=’1′ AND password = ‘x’ OR ‘1’=’1′ is true for every row.
Replacing quotes with your own code fails in surprising cases, such as different character sets and numeric fields. Use parameters, which the database driver implements correctly.
Every database library has parameters: placeholders such as ? or %s or $1. If you see a plus sign or an f-string next to the word SELECT, treat it as a bug.
Every program in this lesson was run while the course was written, with Python 3.13 and only its standard library (http.server, sqlite3, hashlib, hmac), with a real server on a free local port, and cross-checked with curl, openssl or a second implementation. Tools and versions change, so check the official documentation for current behaviour. The attacks in this lesson ran only against an in-memory database created by the lesson. Never test attacks against systems you do not own or have written permission to test.
Practice
Search for every place where your own code builds SQL with string joining, and fix each with parameters. Write a test that sends the six inputs of the lesson to your login function. Add a limit of five failed attempts per account.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is SQL injection?
- Input that changes the meaning of the SQL command
- A database feature
- A kind of index
- A backup method
Data is treated as code.
What is the correct defence?
- Replacing quotes yourself
- Longer passwords
- A bigger server
- Parameterised queries
Values are sent separately from the command.
Why can a column name not be a parameter?
- It is a bug
- It is too long
- Databases forbid names
- Parameters work for values, not names
Use an allow-list.
What did the UNION attack do?
- Deleted a table
- Changed a password
- Read a row from another table
- Nothing
It appended a second query.
Why do honest users hit the bug too?
- They type slowly
- They use old browsers
- A name with a quote breaks the query
- They are blocked
o’brien broke the unsafe query.
Summary
- Never build SQL by joining text and values.
- Parameterised queries keep values as data.
- Allow-list anything that cannot be a parameter.
- Test your defences with attack strings, only on systems you own.
Questions
Are ORMs safe from injection?
Mostly, because they use parameters, but raw query features and string-built fragments can reintroduce the problem. Check the documentation for how to pass values safely.
Is client-side validation enough?
No. Attackers skip the page and send requests directly. Defend in the back end, always.
What else should I know about back-end security?
Hash passwords, use HTTPS, limit database rights, keep software updated and log attacks. The Cybersecurity course covers more.
