HomeBlogHow to Protect Your Web Application...

Engineering Guide · 8 min read · May 21, 2026

How to Protect Your Web Application Against SQL Injection

ORMs eliminate most trivial SQL injection bugs, yet teams still ship exploitable queries through raw reporting expressions, dynamic sorting parameters, and unchecked JSON path lookups. Here is how to lock down every SQL boundary from application code to database roles.

Author
Smit Desai
Published
May 21, 2026
Read time
8 min read
Topic
Security & SEO
Services
Custom Web · Mobile Apps · All Services

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:

  1. Dynamic ORDER BY, GROUP BY, and column selectors built for data tables.
  2. Raw aggregation expressions inside analytics dashboards (whereRaw, selectRaw, $queryRawUnsafe).
  3. JSON/JSONB path queries where a query string key gets interpolated into data->>'${key}'.
  4. 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:

  • LIKE wildcard abuse: Parameterizing WHERE 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 to SELECT, INSERT, UPDATE, and DELETE on 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, selectRaw with $ variables inside double quotes.
  • $queryRawUnsafe in 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.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Infrastructure Proof

300+ WordPress & Cloud Server Fleet

From server-level management of 300+ WordPress sites for a Finland client to PostgreSQL query tuning (3,982 -> 52 queries).

Pillar 2 · Legacy Rescue

Upgrade Old Software (10 Hrs Free)

Audit bottlenecks, eliminate security vulnerabilities, and stabilize production servers—starting with 10 free engineering hours.

01 — Frequently asked questions

security & seo

Does using an ORM like Eloquent, Prisma, or TypeORM guarantee SQL injection protection?

No. ORMs parameterize standard CRUD builders, but developers reintroduce SQL injection whenever they use raw query helpers (DB::raw, whereRaw, $queryRawUnsafe) with string interpolation or pass unvalidated user input as column names.

Can parameterized queries bind column names or table names?

No. SQL bind parameters only represent literal values inside expressions, never identifiers like table names, column names, or ASC/DESC keywords. Use strict allowlists for dynamic sorting and filtering.

What is second-order SQL injection?

Second-order SQL injection occurs when malicious input is safely stored via a parameterized INSERT, then later read back from the database and concatenated into an unsafe raw SQL query inside a cron job, report exporter, or legacy admin screen.

Is escaping quotes with functions like addslashes() safe?

Never rely on manual escaping functions. Character-set mismatches and non-quoted numeric contexts bypass manual escaping easily. Always use native prepared statements with bound parameters.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.