SQL injection is not dead: where it still hides in 2026
Prepared statements and ORMs removed the classic string-glued SQL injection, not the bug class. A taxonomy (in-band, blind, time-based, out-of-band, second-order) and the places it still hides in modern code.
Every few years someone declares SQL injection a solved problem. We have prepared statements. We have ORMs. Framework tutorials use placeholders. And yet SQL injection keeps turning up in vulnerability databases, and the WordPress plugin ecosystem keeps producing new cases.
Parameterised queries fixed one specific mistake: gluing a user-supplied value into a query string. They did nothing for the other parts of a query an attacker can influence, and nothing for the code paths nobody thinks of as “the database layer”. This post maps where SQL injection lives today, with one real, public case and a set of recipes for finding it in your own code.
A little theory: what placeholders protect, and what they don’t
A prepared statement separates code from data. The query text is sent with holes in it, the values are sent separately, and the database never parses a value as SQL. That is a complete fix, for values.
The catch is in that last word. A placeholder can only stand where the SQL grammar expects a literal value: a string, a number, a date. It cannot stand for:
- a column or table name (
ORDER BY ?sorts by a constant, not a column), - a keyword such as
ASC/DESC, or an operator, - a variable-length list like the contents of
IN (...), - a fragment of SQL such as an extra
WHEREclause built by a filter UI.
Each of those has to be assembled as a string, and wherever code assembles SQL as a string, the old bug can come back. ORMs move the problem around rather than removing it: most expose a “raw” escape hatch (whereRaw, orderByRaw, extra(), literal(), text(), .raw(), and developers reach for it when the query gets dynamic, which is also when the input gets interesting.
How data actually comes out: a taxonomy of techniques
Once a parameter is injectable, how an attacker turns that into data depends on what the application hands back. The usual split is by the channel the answer travels on.
| Family | Variant | Needs | Rough speed |
|---|---|---|---|
| In-band | Error-based | DB errors shown to the client | Fast |
| In-band | UNION-based | Query output rendered on the page | Fast |
| Inferential (blind) | Boolean-based | Only a true/false difference in the response | Slow |
| Inferential (blind) | Time-based | No visible difference at all | Slowest |
| Out-of-band | DNS/HTTP exfil | An outbound network channel from the DB | Varies |
In-band: the answer comes back in the response
Error-based. If the database’s error text reaches the client, the error becomes the output channel: coerce the data into a message the engine is forced to print. In MySQL the common trick feeds a subquery into an XML function whose error echoes its argument:
' AND extractvalue(1, concat(0x7e, (SELECT version())))-- -The query fails, and the failure says XPATH syntax error: '~8.0.36'. Turn off detailed errors and this channel closes, which is why blind techniques exist.
UNION-based. When the page renders the query’s rows, UNION SELECT appends attacker-chosen rows to the result set. Two conditions must hold: the injected SELECT needs the same column count and compatible types. Attackers find the count by probing (ORDER BY 5-- - errors, ORDER BY 4-- - doesn’t, so four columns) or with incrementing NULLs, then place output in a column that gets printed:
' UNION SELECT NULL, username, password FROM users-- -The trailing -- - comments out the rest of the original query so the forged tail parses cleanly.
Inferential (blind): you ask yes/no questions
When no output and no errors come back, you can still extract data one bit at a time by asking the database questions whose answer you observe indirectly. It is slow, but deterministic and fully automatable.
Boolean-based blind. The page looks different for a true condition than a false one: a listing appears or vanishes, a word changes. You binary-search each character:
' AND substring((SELECT password FROM users LIMIT 1),1,1) > 'm'-- -If the “found” page comes back, the first character is after m; if the “not found” page comes back, it isn’t. Repeat down to the exact byte, then move to the next position.
Time-based blind. When nothing in the response changes (same page, same status, every time), the observable becomes the clock. You make the database sleep only when your condition is true, and measure how long the response took. Each engine has its own delay primitive:
| Engine | Delay primitive |
|---|---|
| MySQL / MariaDB | SLEEP(5), or BENCHMARK(5000000, SHA1('x')) |
| PostgreSQL | pg_sleep(5) |
| MS SQL Server | WAITFOR DELAY '0:0:5' |
| Oracle | dbms_pipe.receive_message('a', 5) |
' AND IF(substring((SELECT password FROM users LIMIT 1),1,1) > 'm', SLEEP(5), 0)-- -A five-second response means true, an instant one means false. It is the slowest technique (one request per probe, each costing the delay), but it needs the least from the application: no output, no error, not even a visible difference. It is the fallback that works when everything else is closed.
Out-of-band (OOB): make the database phone home
When the response channel is shut entirely (asynchronous processing, a query whose result you never see), you can sometimes still exfiltrate by making the database server itself open an outbound connection, smuggling the secret into the hostname it looks up so the data leaves over DNS or HTTP. The usual primitives are LOAD_FILE() against a UNC path on MySQL (Windows), xp_dirtree on MS SQL Server, and UTL_HTTP / UTL_INADDR on Oracle. The shape is “concatenate the secret into a subdomain of a host you control and trigger a lookup to it”. I describe it here rather than chain it, because OOB depends heavily on DB privileges and egress. The defensive point is simpler: a database with no reason to make outbound connections shouldn’t be able to, and egress filtering turns OOB from silent into blocked and logged.
Second-order: the payload arrives by a safe door
Separate from the channel split above is when the payload runs. In second-order SQLi it is stored safely with a parameterised INSERT, then read back later and concatenated into a different query that isn’t parameterised. Any of the techniques above can then fire on a value the entry point already accepted. It gets its own entry in the map below.
A word on WAF bypass
A firewall that pattern-matches on strings like UNION SELECT or SLEEP( slows an attacker down but does not fix anything. At the awareness level, signatures fall to inline comments (UN/**/ION), case variation (SeLeCt), whitespace swaps (tabs, newlines, /**/ for spaces) and encoding (URL-, hex- or unicode-encoding so the WAF and the database disagree on what the bytes mean). A WAF buys time; the fix belongs in the query.
Where it hides
1. Identifiers: ORDER BY, column and table names
A common modern SQL injection is a sort parameter. A table UI sends ?orderby=created_at&order=desc, and the server does this:
$orderby = sanitize_text_field( $_GET['orderby'] );
$order = $_GET['order'];
$sql = "SELECT * FROM {$table} ORDER BY $orderby $order";sanitize_text_field() is not a SQL escaper, and no escaper would help anyway, because the value is not inside quotes. Anything that parses as an expression is accepted: a subquery, a CASE WHEN ... THEN that sorts differently depending on a secret, or a time delay. Boolean and time-based blind extraction through ORDER BY is slow but entirely practical.
The same applies to “which column to search”, “which table to export”, and dynamic GROUP BY.
2. LIKE wildcards
Parameterising a LIKE query stops injection but leaves a smaller bug: % and _ inside the value are still wildcards. A search for % matches everything, and a lookup that should be exact (WHERE token LIKE ?) turns into a pattern match. That is not code execution, but it is how an “exact match” check becomes an enumeration oracle. Escape wildcards before binding (in WordPress, $wpdb->esc_like()), or use = when you mean equality.
3. IN lists
WHERE id IN (?) with one placeholder does not take an array. So people write "IN (" . implode(',', $ids) . ")" and assume the IDs are integers because they came from a checkbox. Unless every element is cast (array_map('intval', ...)) or given its own placeholder, that is a string-built query with attacker-controlled content.
4. JSON path expressions
Modern databases let you query inside JSON columns (JSON_EXTRACT, ->>, jsonb path operators), and the path is often built from user input, such as a settings key or a filter field name. A placeholder binds the JSON document fine, but the path string gets glued in:
$key = $_GET['field'];
$sql = "SELECT JSON_EXTRACT(data, '$.{$key}') FROM settings WHERE id = %d";$key lives inside the path literal, and in MySQL that literal is still SQL text: a crafted field closes the string and injects. It feels like “just picking a property”, which is why it slips through review. Allowlist the key, or bind the path where the engine supports it.
5. The paths nobody reviews: logging, analytics, queues
Feature code gets reviewed; the code that logs, counts, queues or reports on that feature often does not. Audit trails, download counters and upload bookkeeping tend to be written once with string concatenation, and they frequently see the raw request before the main path’s validation runs. They often run on every request, so without authentication.
6. Second-order injection
A value stored safely with a parameterised INSERT is trusted on the way back out (“it came from our own database”) and concatenated into a different query that isn’t parameterised. The payload sits dormant until a report, cron job or admin screen reads it. Validating the entry point does not help when the entry point was a different, safe query.
7. WordPress: $wpdb->prepare() misuse
WordPress has its own placeholder API, and its misuses are distinctive enough to list separately:
- Placeholders in identifier position.
prepare("... ORDER BY %s", $col)producesORDER BY 'created_at', which sorts by a constant. Developers notice it doesn’t work and switch back to interpolation. %imisunderstood. WordPress 6.2 added%ifor identifiers and it quotes a column or table name correctly. On cores older than 6.2, though, it is a literal%i(silently breaking the query and pushing people back to concatenation), and even when it works it only quotes the name; it does not decide which column a user may name.%iplus a raw request value is still an attacker-chosen identifier, so you still need an allowlist.prepare()called on an already-interpolated string.$wpdb->prepare("SELECT * FROM t WHERE a = '$a' AND b = %d", $b)looks prepared and passes a lazy grep, but$awas spliced in beforeprepare()ever saw it.esc_sql()without quotes.esc_sql()escapes characters that matter inside a quoted string."WHERE id = " . esc_sql($_GET['id'])has no quotes to break out of, so1 OR 1=1passes through untouched.- Undoing magic quotes. WordPress adds slashes to request superglobals by default. Code that calls
stripslashes_deep($_POST)(often for good reasons) removes that accidental protection, and every later concatenation with a “sanitized” value becomes live.sanitize_text_field()does not remove single quotes.
A real case: unauthenticated SQLi through an upload log
The WordPress File Upload plugin (wp-file-upload) combines most of the items on that list in one bug: an unauthenticated SQL injection in versions up to and including 5.1.10, published as CVE-2026-62071 and fixed in 5.2.0. I found it while reading the patch for the earlier CVE, and I covered it in full in the wp-file-upload write-up.
An earlier CVE (CVE-2026-17044, fixed in 5.1.8) had fixed one query that used the upload ID, in wfu_get_userdata_from_uploadid(), by wrapping it in $wpdb->prepare(). The same ID also flowed into a logging function, wfu_log_action(), that the fix did not touch:
$existing = $wpdb->get_row('SELECT * FROM '.$table_name2.' WHERE uploadid = \''.$uploadid.'\' AND property = \''.esc_sql($userdata_field['label']).'\' AND date_to = 0');The chain to reach it:
- The upload handler is registered for unauthenticated visitors (
wp_ajax_nopriv_), and the nonce it needs is printed on any public page that shows the upload form. - The handler calls
stripslashes_deep($_POST), undoing WordPress’s slashing. - The upload ID goes through
sanitize_text_field(), which keeps'intact, and a length check that only requires exactly 10 characters, so a payload such as' OR 1=1#afits. - The value reaches the raw query in the logging path (the call needs a form with user-data fields configured).
The stripslashes_deep() call is what made this exploitable. In other plugins I looked at the same week, sanitize_text_field() feeding a raw query turned out to be safe, because nothing removed the slashes first and WordPress’s magic quotes still escaped the quote.
The same tainted ID was also stored with a safe $wpdb->insert() and later read back into several more raw queries. That is the second-order variant in practice, and there the 10-character limit no longer applies because those reads come from the database. The main feature was patched; the bookkeeping path next to it was not.
How to find it in your own code
Start from the sinks, then check each one’s inputs.
- Grep for string-built SQL. In PHP, look for query calls whose argument contains a
$variable or.concatenation:get_results(,get_row(,get_var(,get_col(,query(. In other stacks, look forexecute(f", template literals inquery(\``, and the ORM raw methods (whereRaw,orderByRaw,raw(,extra(,literal(,text(`). - Read every
prepare()call’s first argument. If the format string contains$or{$...}other than a trusted table name, it is a candidate. Treat'$var'inside a prepared string as an automatic finding. - Hunt identifier parameters. Grep request handling for
orderby,order,sort,column,field,group,dir, and follow them to the query. - Check
esc_sql()callers for quotes. Anesc_sql()result not wrapped in'...'is unprotected. - Find who removes slashes.
stripslashes_deep,wp_unslashon whole superglobals, orstripslashesnear user input means every later concatenation must be judged without the magic-quotes safety net. - Follow values through storage. For every column written from user input, find where it is read and check whether those reads build SQL as strings.
- Prioritise unauthenticated reach. In WordPress, start from
wp_ajax_nopriv_actions and REST routes withpermission_callback => '__return_true', then look at what they log. - Confirm with the database, not the response. Turn on the MySQL general log on a test install and read the query that actually ran. That ends arguments about whether a quote was escaped. It is how I confirmed the wp-file-upload bug.
- Test blind by differential, not by output. When nothing comes back, confirm it the way you’d confirm a complexity DoS: send a true condition and a false one and compare. Boolean blind shows a page difference; time-based shows a response-time difference, where the server did measurably more work only when your predicate was true. A clean true/false divergence on an otherwise identical page is the signal.
- Automate the repetitive part, but understand it first. Blind extraction is tedious by hand, and
sqlmapdoes that enumeration once you’ve found an injectable parameter. Use it to confirm impact on your own systems. The techniques above are what it runs under the hood, and knowing them is how you tell a real finding from a false positive.
The fix
Parameterise every value, without exception. That includes values that “came from the database”, values that “are always integers”, and values in log and analytics queries. In WordPress, that means $wpdb->prepare() with %s, %d and %f, or $wpdb->insert()/update()/delete() with format arrays.
Allowlist identifiers. For sort columns, directions and table choices, map user input to a fixed set of known-good strings and never pass the input through:
$columns = [ 'date' => 'created_at', 'name' => 'title', 'size' => 'file_size' ];
$orderby = $columns[ $_GET['orderby'] ?? '' ] ?? 'created_at';
$order = ( strtoupper( $_GET['order'] ?? '' ) === 'ASC' ) ? 'ASC' : 'DESC';
$sql = $wpdb->prepare( "SELECT * FROM {$table} WHERE owner = %d ORDER BY $orderby $order", $user_id );Use %i where you can rely on it. WordPress 6.2 added an %i placeholder for identifiers, which quotes a table or column name correctly. Use it only if your plugin really requires 6.2 or newer: on older cores, %i is not recognised as a placeholder and the query will not do what you expect. It also doesn’t decide which column a user may sort by. An allowlist does that.
Expand IN lists safely. Cast each element (array_map('absint', $ids)) or generate one placeholder per element and bind them all.
Escape LIKE input. $wpdb->prepare("... LIKE %s", '%' . $wpdb->esc_like($term) . '%').
Validate formats you already know. If an ID is ten alphanumeric characters, enforce that with a strict pattern at the entry point. In the wp-file-upload case, the plugin already had a helper that stripped IDs to [A-Za-z0-9]; it just wasn’t applied to this one.
Takeaway
Placeholders protect values, and SQL injection now lives everywhere else.
Allowlist identifiers, parameterise every value including the ones you read back from your own tables, and audit the logging paths as carefully as the feature.