SQL Injection: Attack and Defense
SQL injection (SQLi) has been the number one web vulnerability for years: attackers smuggle SQL code into inputs.
How it works
// Vulnerable (string concatenation):
SELECT * FROM user WHERE name = '" + input + "'
// Input: ' OR '1'='1 → SELECT * FROM user WHERE name = '' OR '1'='1'This allows reading, changing or even dropping entire tables.
Defense
- Prepared statements (parameterized queries) — the most important defense. PHP: PDO, Python: DB-API parameters, Java: PreparedStatement.
- ORMs (Eloquent, SQLAlchemy, Hibernate) build queries safely.
- Least privilege: DB users get only the needed rights.
- Input validation as a second line of defense — but never instead of prepared statements.
Detection
Pen tests, DAST scanners (OWASP ZAP), code review for string concatenation in SQL. WAFs (ModSecurity) block known patterns but do not replace clean code.
See also: System Administration.