Which is the correct primary defense against SQL injection?
Options
- Escaping the quotes in the user input by hand
- Parameterized queries or prepared statements (Correct option)
- Hiding detailed error messages from the users
- Using POST requests instead of GET requests
Answer
Parameterized queries / prepared statements (or an ORM that uses them)
Why
SQL injection happens when user input is glued into SQL text, so a clever input changes the query itself (e.g. ' OR 1=1 -- returns all rows, or '; DROP TABLE users; --).
With parameterized queries, the SQL and the values are sent separately; the database never runs the input as code.
Manual escaping is easy to get wrong. Also give the app's DB user only the permissions it needs.
Remember
Never build SQL with string formatting; use parameters.