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:

Make a list with file and line number.

Step 2: prioritise (minutes)

Fix in this order:

PriorityQuery uses...
1Values typed by users: forms, search boxes, URLs
2Values from files or other systems
3Values 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:

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

Timeline for a small project

DayWork
1Find and list all queries; fix priority 1
2Fix priorities 2 and 3; handle tricky cases
3Test 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.

Related pages on this site