Application Security

Prevent SQL Injection with Safe Query Design

Use parameterized queries, allowlisted identifiers and least-privilege database accounts to prevent SQL injection.

SQL injection occurs when untrusted input changes the structure of a database statement. The primary defense is to keep SQL code separate from data. Escaping strings manually is fragile and should not replace parameterized queries.

Use prepared statements

With PDO, prepare the SQL statement and bind values through parameters. Parameters represent data values, not SQL identifiers or keywords. This distinction matters when a page allows sorting by a column: the requested column name must be selected from a fixed allowlist rather than bound as a value.

Build dynamic queries deliberately

For optional filters, add only known SQL fragments and bind every supplied value. For an IN clause, create the correct number of placeholders and bind each element. Avoid concatenating raw request values into WHERE, ORDER BY, LIMIT or table-name fragments.

Apply least privilege

The application database account should have only the permissions it needs. A public-facing website rarely needs database administration privileges. Separate migration credentials from runtime credentials where operationally practical.

Test and review

Search for query construction that includes request parameters, cookies or headers. Include tests for quotes, comment markers, encoding edge cases and unexpected types. Error responses should not reveal SQL statements or schema details.

Checklist

  • Parameterize all data values.
  • Allowlist dynamic identifiers and sort directions.
  • Avoid manual escaping as the main defense.
  • Use least-privilege database accounts.
  • Review and test every dynamic query path.
Share this page Help other developers discover this resource.