What Is SQL Injection?
SQL Injection happens when user input is directly inserted into a database query without proper validation or escaping. An attacker can change the meaning of the query and make the database do things it was never supposed to do.
Example: Unsafe Login Logic (Conceptual)
Imagine a login form like this:
On a vulnerable server, the backend might build a query like:
SELECT * FROM users WHERE username = 'USER_INPUT' AND password = 'PASS_INPUT';
If the code simply drops the raw text from the form into the query, a malicious user could type something that changes the logic of the query.
Conceptual Injection Example
A classic malicious input (do not use this on real systems) might look like:
Username: ' OR '1'='1
Password: anything
The resulting query becomes:
SELECT * FROM users
WHERE username = '' OR '1'='1'
AND password = 'anything';
Because '1'='1' is always true, this can trick a poorly written system
into thinking the login succeeded.
This is why SQL Injection is dangerous and why we never trust raw user input.
Safer Approach: Prepared Statements
Instead of building queries by string concatenation, we use parameters:
-- Example in pseudo‑code / parameterized style:
query = "SELECT * FROM users WHERE username = ? AND password = ?"
db.execute(query, [username_input, password_input])
Here, the database treats user input as data, not as part of the SQL command. This prevents the input from changing the structure of the query.
Key Takeaways for Students
- Never trust user input.
- Never build SQL queries by concatenating strings.
- Use prepared statements / parameterized queries.
- Input validation and escaping are critical.
- Security is part of being a good programmer, not an optional extra.