Knowledgebase

Writing Secure Database Queries Print

  • developersgitdeployment, developers, database, security, errors, guide, howto, solution
  • 0

Preventing the most damaging class of vulnerability.

SQL INJECTION

Never build a query by concatenating user input into a string. Use prepared statements with bound parameters.

This single practice eliminates the entire class of attack. PDO and MySQLi both support it, and every framework provides it.

WHAT COUNTS AS USER INPUT

Anything from a form, a URL parameter, a cookie, a header, an API response, or the database itself. Treat all of it as untrusted.

FRAMEWORK QUERY BUILDERS

These parameterise automatically, which is why using them is safer than writing raw SQL.

Be careful with raw expressions inside a query builder, which bypass the protection.

DATABASE PRIVILEGES

The application's database user needs privileges on its own database only. Never root, never access to other databases.

This limits the damage if an injection does occur.

ERROR MESSAGES

Never display database errors to visitors. They reveal table structure and query fragments. Log them instead.

TESTING

Try entering a quote character in your form fields. If it produces a database error, the query is not parameterised.


Was this answer helpful?
Back

Are you happy with your experience? Leave us a review on Trustpilot.


Trustpilot