SQL Injection
SQL injection is a common attack in which malicious input is smuggled into a query, and it is prevented by using parameterized queries instead of building SQL from raw strings.
What Is SQL Injection?
SQL injection happens when an application builds a SQL statement by pasting user input directly into the query text. If the input contains SQL syntax, it can change what the query does. Attackers use this to read data they should not see, bypass logins, modify records, or even destroy tables. It remains one of the most serious and widespread security risks in software that talks to a database.
The core problem is that the database cannot tell the difference between the SQL your code intended and the SQL an attacker slipped in through an input field. To the database, it is all just one string to execute.
How an Attack Works
Imagine a login form that builds a query by concatenating whatever the user typed. The code might glue the username and password straight into the SQL text.
Unsafe query built from string concatenation
-- The application pastes user input directly into the SQL:
SELECT *
FROM Users
WHERE Username = 'alice' AND Password = 'secret';Now suppose an attacker types the password as: ' OR '1'='1. Because the value is pasted in as-is, the resulting query changes meaning entirely and the condition becomes always true, returning every user row and letting the attacker in without a valid password.
The same query after malicious input is injected
-- Attacker entered: ' OR '1'='1 as the password
SELECT *
FROM Users
WHERE Username = 'alice' AND Password = '' OR '1'='1';The Fix: Parameterized Queries
The reliable defense is to use parameterized queries, also called prepared statements. You write the SQL with placeholders and pass the user values separately. The database driver then sends the query structure and the data apart from each other, so the input is always treated as a value and never as executable SQL. Even the ' OR '1'='1 string simply becomes a password value that fails to match.
Safe query using placeholders (parameters)
-- The ? marks are placeholders; values are bound separately
SELECT *
FROM Users
WHERE Username = ? AND Password = ?;
-- Named placeholders work the same way in many databases:
SELECT *
FROM Users
WHERE Username = :username AND Password = :password;- Always use parameterized queries or prepared statements for any value that comes from outside your code.
- Validate and constrain input (expected length, type, and format) as an extra layer, not as the only defense.
- Grant each database account the least privilege it needs, so a compromised query can do less damage.
- Avoid exposing raw database error messages to users, since they can reveal table and column names.
Exercise: SQL Injection
What is SQL injection, at its core?