← All posts
Web security

What is SQL injection? The concept, the boundary and the fix

SQL injection explained by mechanism. Where user input turns into code, why validation does not fix it, why parameterised queries do, and what the fix costs.

SQL injection is what happens when a string the user typed gets pasted into a database query and the parser reads part of it as SQL instead of as data. That is the whole concept. If you searched for "what is sql injection" expecting something exotic, the honest answer is that it is a trust boundary drawn in the wrong place: the application treats a query as one thing when it is really two, your code and their input, glued together before the parser sees either.

What is SQL injection: the point where input becomes code

The vulnerable pattern:

query = "SELECT * FROM users WHERE username = '" + username + "'"
cursor.execute(query)

The developer thinks of username as a value. The database receives one string and parses it, with no way to tell which characters came from the developer and which from the request. That information was destroyed at concatenation.

So the boundary is not the network edge or the form field. It is the point where the query string is assembled. If your code and their text meet there as concatenation, the user is co-authoring your SQL.

A marker shows this without harming anything. Take a deliberately vulnerable practice app (PortSwigger's Web Security Academy has them, or run OWASP Juice Shop or DVWA locally) and submit a username that is a single quote:

'

The query becomes SELECT * FROM users WHERE username = ''' and the parser chokes. You get a syntax error, often echoed straight into the page: You have an error in your SQL syntax or unterminated quoted string. That error is the proof: one character changed the shape of the statement, not just a value inside it. The classic tautology (' OR '1'='1) comes next, turning a lookup for one user into one that matches all of them. I'm not walking further down that road; recognising the boundary is the point.

Why input validation is not the fix

The most common advice is to "sanitise input": strip quotes, block the word SELECT, reject --. I think this advice is wrong, and not slightly wrong. It is a control that looks like a fix and is mostly theatre.

Validation tries to predict every string that could change the query's shape and refuse it. But the dangerous set depends on the engine, its version, the character set, the context the input lands in (string literal, numeric comparison, identifier, LIKE pattern) and the encoding layers between form and query. You are enumerating badness in a space you do not control, and the attacker needs one gap.

There are also legitimate users called O'Brien.

Validation has its place: an age should be an integer, a sort column should be one of four allowed names. That is defence in depth around the fix, not the fix.

Parameterised queries are the fix

A parameterised query (prepared statement, bound parameters) sends the SQL and the data to the database separately:

cursor.execute("SELECT * FROM users WHERE username = %s", (username,))

The database parses the statement first, with a placeholder where the value will go. The parse tree is now fixed. Then the value is bound in, as data. A quote in username arrives after parsing has finished, so there is no parser left for it to confuse. It is not escaped or filtered. It simply never gets the chance to be read as SQL.

Escaping tries to make data safe to parse. Parameterisation means the data is never parsed at all. That is why "we escape everything" is a yellow flag in a code review rather than a reassurance.

ControlWhat it doesWhat it costsVerdict
Input validationRejects strings that look dangerousCheap to write, breaks legitimate input, never completeSecond layer, not a fix
Escaping before concatenationMakes quotes inert for one engine, one contextFragile, easy to miss a call siteStopgap while refactoring
Parameterised queriesSeparates statement from data at the protocol levelRefactoring every string-built queryThe fix
WAF rulesPattern-matches known payloadsLicence, false positives, bypassableWeak secondary signal
Least-privilege DB accountLimits what a successful injection reachesSome operational workBlast-radius control, do it anyway

Where your ORM stops protecting you

If you use an ORM, most of your queries are already parameterised. User.objects.filter(username=name) in Django or prisma.user.findMany({ where: { username } }) both bind the value. The holes are at the edges, where the ORM hands you a string and trusts you:

  • Raw query methods. .raw(), $queryRawUnsafe, sequelize.query() with interpolation, knex.raw() with a template string. Each exists so you can write SQL the ORM cannot express, and each will happily concatenate.
  • ORDER BY and column names. Drivers cannot parameterise an identifier, so ORDER BY ${sortField} from a query parameter is concatenation dressed up. The fix is a hard allowlist in your code that maps the user's choice to a fixed column name.
  • Stored procedures that build SQL internally. Parameterising the call does not help if the procedure concatenates.

Detecting it: errors first, WAF second

The strongest free signal is your own database error log. A healthy application almost never produces SQL syntax errors in production. When unterminated quoted string or syntax error at or near starts appearing, someone is probing. Alert on those errors, and make sure they are not echoed into HTTP responses, because a verbose error page is the attacker's best debugging tool.

Request logs help too: SLEEP(, pg_sleep( or WAITFOR DELAY in a search parameter are time-based probes against an app that doesn't leak errors.

A WAF catches textbook payloads and misses anything slightly encoded or engine-specific. Treat its alerts as a reason to look, never as evidence you are protected. A regex against a parser loses; the parser is more creative.

What the fix costs

Nobody argues with parameterisation in principle. The resistance is practical: an old codebase has hundreds of string-built queries, some in stored procedures, some in report generators that assemble WHERE clauses dynamically. "Append a condition if the filter is set" is easy with strings and awkward with placeholders. Query builders (Knex, SQLAlchemy Core, jOOQ) exist for exactly this.

Prioritise by exposure: unauthenticated paths first, admin-only last. And run the application's database account with least privilege, so the query you missed can read one table rather than drop the schema.

It is the same argument as in Your CSP probably does nothing: a control only counts if it operates at the layer where the attack happens. And if an LLM writes SQL from natural language anywhere in your stack, the problem returns with a new name. What is prompt injection, really is the same boundary with a model in place of a parser, and the AI Audit will flag it.

Frequently asked questions

Is SQL injection still a real problem? The fix is well known, which is not the same as applied. New code through an ORM is usually safe by default. Old code, raw queries, dynamic sorting and stored procedures are where it keeps turning up.

Does using an ORM mean I am safe? For the queries the ORM builds, mostly yes. Not for raw query methods, string-built ORDER BY, dynamic table names or stored procedures that concatenate internally. Audit every call to the raw-query method.

Can I just escape the quotes instead of rewriting queries? You can, and it reduces the risk, but it has to be correct for every engine, context and call site. Parameterisation removes the problem rather than patching it. Treat escaping as a stopgap while you refactor.

Where can I practise this legally? PortSwigger's Web Security Academy at portswigger.net/web-security has free SQL injection labs. Or run OWASP Juice Shop or DVWA on your own machine. Never test a site you don't own or have written authorisation to test.


Open the repository you work in most. Grep for your ORM's raw-query method, and for ORDER BY followed by a template placeholder or concatenation. Read each hit and ask one question: can text from a request reach the parser as anything other than a bound parameter? That is the boundary. Find it before someone else does.

Web security
One unauthenticated request. Any PHP that serves the web. Patch tonight.Web security

PHP2Shell: two unauthenticated RCE flaws in PHP, and what to patch tonight

CVE-2026-109618 and CVE-2026-109619 let an attacker run code on a PHP web server with a single unauthenticated request. Here is the mechanism, the fixed versions, and why mod_php setups are in the most danger.

It looks strict. It permits everything. Which is which?Try it

Read this CSP: four policies, which one actually stops an XSS?

Four Content-Security-Policy headers that all look strict. Predict what each one really permits before you read the answers, then paste any of them into the CSP builder to confirm.

Three of these four tell you how to forge them. Can you see it?Try it

Read this JWT: four tokens, which one would you trust?

Four JSON Web Tokens, three with a weakness you can see from the header and payload alone. Spot each flaw before the answers, then paste any token into the JWT inspector to confirm — and read the one-line server fix for each.