Every developer learns early not to write "SELECT * FROM users WHERE email = '" . $email . "'". Yet SQL injection still shows up in real production audits—not because engineers forgot what a prepared statement is, but because complex business features push teams into raw SQL escapes, dynamic table views, and multi-tenant reporting screens.
Recognizing where modern frameworks stop protecting you is the difference between feeling safe behind an ORM and actually being safe under the OWASP Top 10 injection rules.
1. Why Modern Codebases Still Ship SQL Injection
When I audit legacy or rapidly built SaaS repositories, SQL injection almost never appears in the login form. It hides in four specific corners:
- Dynamic
ORDER BY,GROUP BY, and column selectors built for data tables. - Raw aggregation expressions inside analytics dashboards (
whereRaw,selectRaw,$queryRawUnsafe). - JSON/JSONB path queries where a query string key gets interpolated into
data->>'${key}'. - Second-order SQLi, where an admin report concatenates a company name that was originally saved safely during signup.
2. Parameterized Queries Done Right (and Wrong)
Prepared statements work because the database driver sends the SQL structure and the data values separately. The SQL parser compiles the execution plan before seeing user input, making it impossible for a value to mutate query syntax.
PHP / PDO Example
// Vulnerable: string concatenation lets input alter SQL logic
$stmt = $pdo->query("SELECT id, email FROM users WHERE status = '{$_GET['status']}'");
// Safe: native prepared statement with strict binding
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare('SELECT id, email FROM users WHERE status = :status LIMIT 50');
$stmt->execute(['status' => $status]);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
Notice PDO::ATTR_EMULATE_PREPARES => false for MySQL/MariaDB. Disabling emulation forces the database engine itself to parse the prepared statement separately rather than letting the client library simulate bindings.
Node.js (pg) Example
// Vulnerable: template interpolation inside SQL text
await pool.query(`SELECT id, total_cents FROM orders WHERE org_id = ${orgId}`);
// Safe: positional parameters ($1, $2)
const { rows } = await pool.query(
'SELECT id, total_cents FROM orders WHERE org_id = $1 AND status = $2 LIMIT 50',
[orgId, status]
);
3. Handling Dynamic Columns, IN Clauses, and LIKE Searches
Because SQL placeholders cannot parameterize identifiers (column names, table names, sort directions), developers frequently fall back to string interpolation for sortable tables.
Safe Dynamic Sorting and Filtering in Laravel
$sortMap = [
'date' => 'orders.created_at',
'amount' => 'orders.total_cents',
'customer' => 'customers.company_name',
];
$column = $sortMap[$request->input('sort')] ?? 'orders.created_at';
$direction = $request->input('dir') === 'asc' ? 'asc' : 'desc';
$orders = Order::query()
->where('organization_id', $request->user()->organization_id)
->orderBy($column, $direction)
->paginate(25);
Two additional edge cases deserve attention:
LIKEwildcard abuse: ParameterizingWHERE name LIKE ?prevents syntax injection, but a user searching for%%%%%can trigger expensive full-table scans. Escape%and_inside the search term before wrapping it in%...%, and enforce a minimum query length.- Dynamic
IN (...)lists: Never implode an array of IDs into a raw string (implode(',', $ids)). Use array bindings (whereIn('id', $ids)or= ANY($1::int[])in PostgreSQL) after validating that elements are integers or UUIDs.
4. Defense-in-Depth Comparison Table
Parameterized queries are your primary control, while database permissions and isolation reduce the blast radius if a single developer slips up in a raw report query.
| Defense Layer | What It Prevents | What It Does Not Prevent | Implementation Cost |
|---|---|---|---|
| Parameterized Queries / Prepared Statements | Syntax injection in values (WHERE, INSERT, UPDATE) |
Unsafe dynamic identifiers (ORDER BY), raw SQL helpers |
Low (default habit) |
| Strict Identifier Allowlists | Injection in ORDER BY, GROUP BY, JSON keys |
Missing tenant ownership checks (IDOR) | Low (small lookup map) |
| Least-Privilege DB User | DROP TABLE, INTO OUTFILE, cross-schema reads |
Unauthorized SELECT/UPDATE inside app tables |
Low (migration vs app role) |
| PostgreSQL Row-Level Security (RLS) | Cross-tenant data leaks even on buggy raw queries | Misconfigured session context variables | Medium (schema design) |
| Static Analysis / SAST in CI | Merging raw interpolated SQL into main |
Runtime logic bugs in stored procedures | Low–Medium (CI rule) |
Separating Migration Roles From Runtime Roles
Your web application worker almost never needs DROP, ALTER, CREATE, or GRANT privileges. Create two database users:
app_migrator: used only during CI/CD release steps to run schema migrations.app_runtime: restricted toSELECT,INSERT,UPDATE, andDELETEon application tables, with zero access to filesystem functions or system catalogs.
5. Catching Hidden Injection Before Deployment
When rescuing older PHP or Node applications—especially legacy systems built before strict ORM conventions—manual grep sweeps quickly reveal where risk lives. Look for:
DB::raw,whereRaw,orderByRaw,selectRawwith$variables inside double quotes.$queryRawUnsafein Prisma or.query(with backtick template literals in Node.sprintf("SELECT ... %s", ...)inside legacy cron scripts and CSV export jobs.
Pair static scanning with automated security tests that send ' OR '1'='1, 1; SELECT pg_sleep(5)--, and invalid sort keys into your search and export endpoints. If a test times out or returns a 500 SQL syntax error instead of a clean 422 validation failure, you found a leak before an attacker did. For broader framework checks, review our complete Laravel security audit checklist.
Fixing Legacy Query Layers With SmitDev
Untangling raw SQL in an active production codebase requires care: one broken report query can stall finance operations or corrupt multi-tenant views. At SmitDev, I regularly step into aging applications through legacy software upgrades and custom web application development to replace brittle string-built queries with typed, parameterized query layers and least-privilege database roles.
You can engage SmitDev directly without agency overhead:
- $55/day (8–9 hours of dedicated engineering) to audit raw SQL hotspots, refactor dangerous endpoints, and add automated regression tests.
- $1,999/month for dedicated ongoing delivery, performance tuning, and security maintenance.
If you have legacy reporting endpoints or complex search builders you want reviewed and hardened, schedule a technical call with SmitDev.