Rolling Out Placeholders Across an Existing Beginner Project
Many first projects build SQL by gluing strings together. It works until someone types an apostrophe, or worse, until someone tries SQL injection. This guide is a step plan for fixing an existing small project, safely and in order.
Step 1: find every query (about an hour)
Search your code for SQL being assembled from pieces. Useful searches:
grep -rn "SELECT\|INSERT\|UPDATE\|DELETE" --include="*.py" .
Look especially for:
+joining strings that contain SQL- f-strings or
format()with SQL inside %formatting into SQL strings
Make a list with file and line number.
Step 2: prioritise (minutes)
Fix in this order:
| Priority | Query uses... |
|---|---|
| 1 | Values typed by users: forms, search boxes, URLs |
| 2 | Values from files or other systems |
| 3 | Values from your own code only |
Everything gets fixed, but the first group is where attacks come from.
Step 3: rewrite each query (a few minutes each)
Before:
cur.execute(f"SELECT * FROM users WHERE email = '{email}'")
After:
cur.execute("SELECT * FROM users WHERE email = ?", (email,))
Rules while rewriting:
- Remove the quotes around the value; the driver handles them.
- One placeholder per value, in the same order as the values.
- Use your driver's placeholder style:
?for sqlite3,%sfor psycopg,$1for node-postgres.
Step 4: handle the tricky cases
Table or column names chosen by users, for example a "sort by" dropdown. Placeholders cannot be used for names. Use an allow-list:
allowed = {"name": "name", "date": "created_at"}
column = allowed.get(sort, "name")
cur.execute(f"SELECT * FROM notes ORDER BY {column}")
Only known, fixed names can reach the SQL.
LIKE searches: put the wildcards in the value, not the SQL: ("%" + term + "%",).
Lists for IN: build one placeholder per item, such as ", ".join("?" * len(ids)), and pass the values separately.
Step 5: test (an hour)
For each fixed query, try values containing an apostrophe (O'Brien), a percent sign and the classic ' OR '1'='1. The query should either find nothing or find the literal text, never everything.
Step 6: keep it fixed
- Add a note to your project's README: "always use placeholders".
- When reviewing your own changes, search the diff for SQL built with
+or f-strings. - Consider using your framework's query tools, which use placeholders by default.
Timeline for a small project
| Day | Work |
|---|---|
| 1 | Find and list all queries; fix priority 1 |
| 2 | Fix priorities 2 and 3; handle tricky cases |
| 3 | Test and add the README note |
Further reading
Breaking and fixing a tiny login form shows the attack in a safe, local exercise, and the one-page brief explains the risk to non-technical teammates.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.