← Web Application Security tutorial
Web Application Security
SQL Injection
A web app usually builds a database query using something the user typed — a username, a search term. SQL injection happens when that input is glued directly into the query string instead of being treated as pure data, letting an attacker's input change what the query actually does.
A classic example: a login check built as a string.
# Vulnerable — the raw username/password are pasted into the query text
query = f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'"
# An attacker enters this as the "username":
# admin' --
# The query becomes:
# SELECT * FROM users WHERE username = 'admin' --' AND password = '...'
# Everything after -- is a SQL comment, so the password check never runs.
# Fixed — a parameterized query keeps input separate from the query structure
cursor.execute(
"SELECT * FROM users WHERE username = %s AND password = %s",
[username, password],
)
The vulnerable query lets the attacker's input change the SQL itself, bypassing the password check entirely. The parameterized version passes username and password as plain data — no matter what characters they contain, they can never change the query's structure.