How the Attack Works
SQL injection happens when user input is glued directly into a query string. If a login query concatenates a username field, an attacker can supply input that closes the intended clause and appends their own, turning a lookup into a data dump or a deletion.
The root cause is mixing code and data in the same string. The database cannot tell which characters were meant as query structure and which were untrusted input.
The Reliable Defense
- Use parameterized queries, also called prepared statements, where placeholders carry the data separately from the query text.
- The driver sends the query plan and the values apart, so input can never change the query structure.
- Prefer an ORM or query builder that parameterizes by default rather than hand built strings.
Defense in Depth
Parameterization is the primary control. Add least privilege database accounts so a compromised query cannot drop tables, and validate input shape where it makes sense. Escaping by hand is error prone and should be a last resort.
Key idea
SQL injection comes from mixing code and data in one string, and parameterized queries fix it by sending the query structure and the untrusted values separately so input can never become executable SQL.