guides · 2026-11-14
How to Fix SQL Injection in AI-Generated Code (Not Just Detect It)
Published 2026-11-14 · Reviewed 2026-11-14 · By the Ingenious AI team
The short answer
The fix is never escaping — it is parameterization: the query structure is sent to the database separately from the values, so input can never become SQL. Convert every interpolated, concatenated or formatted query to placeholders ($1, ?, :name), including the ones hiding in ORDER BY and LIKE clauses, then prove each fix by running the classic ' OR '1'='1 payload against it and watching it match nothing.
Check your own app free: paste your code or enter your site URL on the Vibe-Code Audit homepage — the free scan checks for exposed secrets, injection flaws, XSS patterns, missing headers and exposed .env/.git paths, with a copy-paste fix for every finding. No credit card.
What is SQL injection?
a flaw where attacker-controlled text is stitched into a SQL statement and parsed as code rather than data, letting the attacker rewrite the query's logic — bypass logins, dump tables, or modify rows. Parameterized queries (prepared statements) kill the class by keeping code and data in separate channels.
Recognising every shape the generator produces
AI models produce injection in at least four costumes. The f-string: SELECT ... WHERE email = '{email}'. The concatenation: "SELECT ... WHERE id = " + req.params.id. The percent-format and .format() variants, which look tidier and are identically vulnerable. And the subtle one: an ORM call with a raw fragment — .extra(), sequelize.literal(), order_by built from a request parameter — where 95% of the file is safe and one clause is not. Vibe-Code Audit's core detectors carry separate patterns for the f-string/format shape and the concatenation shape because they hide differently in review.
Sweep mechanically before fixing by hand: grep for SELECT, INSERT, UPDATE and DELETE near string-building operators, and for every raw-query escape hatch in your ORM. The inventory is the work; individual fixes take minutes each.
The conversion, language by language
Python (psycopg): cursor.execute("SELECT * FROM users WHERE email = %s", (email,)) — the driver binds the value; never use % formatting yourself, which recreates the bug with extra steps. Node (pg): client.query('SELECT * FROM users WHERE id = $1', [id]). PHP (PDO): prepare the statement with :email and bindValue. Django and SQLAlchemy users: pass parameters through .raw(sql, params) / text() with bindparams rather than formatting the string first.
Two places placeholders cannot go: identifiers (table and column names) and keywords (ASC/DESC). For sortable columns — the classic generated-code trap — validate the requested column against a fixed allow-list mapping to real column names, and do the same for sort direction. LIKE patterns accept placeholders, but escape %, _ and the escape character in the user's term, or their wildcard becomes your full-table scan.
Proving the fix instead of believing it
For each converted query, run the payloads: ' OR '1'='1, ' OR 1=1 --, and a UNION SELECT probe appropriate to the endpoint. Before the fix, the login bypass returns a row; after, the same payload is treated as a literal string that matches no user — which is the entire point, demonstrated. Save these probes as regression tests: injection has a habit of returning when a later AI edit 'simplifies' the query back into an f-string, and a failing test is the only reviewer that never gets tired.
Also test the boring paths: names with apostrophes (O'Brien) must still work after parameterization — they will, which is a pleasant side effect: the secure version is also the correct version for real user data.
The copies the first fix missed
Generated code duplicates. The same vulnerable query often lives in the admin route, the export script, the seed file and the 'v2' endpoint the model created instead of editing the original. After the main sweep, re-run the scan: Vibe-Code Audit flags remaining string-built queries per location, and a clean re-scan — not your memory of the sweep — is the completion evidence. Pay special attention to reporting and search features, where models reach for string building because the WHERE clause is dynamic; dynamic clauses are built by composing parameterized fragments, never by interpolating values.
Worked example: LedgerLite's invoice search
LedgerLite (fictional), a bookkeeping tool with 620 users, scanned its backend and found 9 string-built queries: 6 f-strings, 2 concatenations and one ORM raw fragment in a report export. The worst was invoice search: entering ' OR '1'='1 into the search box returned every customer's invoices — 4,318 rows in the demo. The team converted all 9 to bound parameters over two days (the report export needed an allow-list for its sortable columns), added the three classic payloads as automated tests for the search and login endpoints, and re-scanned clean: score up from 52/100 to 91/100, with the remaining points lost to headers, not queries.
Your five-action checklist
- Inventory every raw query: grep for SQL keywords near f-strings, +, % and .format, plus your ORM's raw/literal escape hatches.
- Convert each one to bound parameters using your driver's placeholder syntax — never hand-escape or string-format values in.
- Handle identifiers separately: allow-list sortable columns and directions instead of parameterizing the impossible.
- Prove each fix with ' OR '1'='1 and a UNION probe, and save those probes as regression tests.
- Re-scan the whole codebase to catch duplicated copies in admin routes, exports and scripts; a clean scan is the finish line.
Sources
- CWE-89: Improper Neutralization of Special Elements used in an SQL Command, MITRE's weakness entry for SQL injection and its mitigations: cwe.mitre.org, 2026
- PortSwigger Web Security Academy — SQL injection, the reference tutorial on how SQL injection works and how parameterized queries prevent it: portswigger.net, 2026
- OWASP Top 10, the OWASP Foundation's standard awareness list of the most critical web application security risks: owasp.org, 2021
Frequently asked questions
Is escaping quotes with a library good enough?
It is fragile: escaping depends on the database, encoding and context, and one missed case reopens the hole. Parameterization removes the class structurally — values are never parsed as SQL at all.
My ORM 'prevents injection'. Why did the scan flag my code?
ORMs protect the queries they build. The flags land on the escape hatches — raw(), literal(), extra(), string-built fragments — where generated code steps outside the ORM's protection while keeping its reassuring syntax.
Can I parameterize a dynamic WHERE clause?
Yes: build the clause from fixed fragments with placeholders, adding a fragment only when its filter is present, and bind all values in order. The structure is code you wrote; the values stay data.
What about table names from user input?
Never bind them (drivers refuse) and never interpolate them raw. Map user choices through a fixed dictionary: {'date': 'created_at', 'total': 'amount'} — anything not in the map is rejected.
Does parameterization hurt performance?
Prepared statements are typically as fast or faster — the database can cache the query plan. The security win costs nothing measurable at small-app scale.
Related guides
- NoSQL Injection: How a MongoDB Login Falls to a Single $ne Operator
- SSRF in AI-Generated Code: When Your App Fetches Any URL a User Gives It
- Server-Side Template Injection in Flask Apps Built With AI
- Why pickle.loads and yaml.load Turn User Data Into Code Execution
- JWT alg=none and Key Confusion: How Attackers Forge Any User's Token
- How to Fix CORS Errors Without Opening Your API to Every Website
- 7 Security Mistakes AI Coders Keep Making
- Supply-Chain Attacks in the AI-Coding Era
- Secret Hygiene: Stop API Key Leaks
- What Code Scanners Can't Find
- Bolt.new Pre-Deploy Security Checklist
- Cursor-Generated Code Review Checklist
Browse the full library on the guides index, run the checks in the launch audit, or compare plans on pricing.
Informational explainer, not a security guarantee. Scan your code free before every deploy.