Contents
🛡️ Understanding SQL Injection (SQLi)
What is SQL Injection?
SQL Injection (SQLi) is a code injection vulnerability that allows attackers to interfere with the queries that an application makes to its database. By manipulating input fields (e.g. login forms, search boxes), a malicious actor can insert or “inject” SQL commands that the backend will unknowingly execute.
If left unpatched, SQLi can allow:
- Unauthorised viewing of data (sensitive user details, passwords)
- Deletion or modification of records
- Full system compromise
🔍 Real-World Examples of SQL Injection
🧪 Example 1: Bypassing Login Authentication
Input:
Username: admin
Password: ' OR '1'='1This input alters the query to:
SELECT * FROM users WHERE username = 'admin' AND password = '' OR '1'='1';Since '1'='1' is always true, the login succeeds without a valid password.
🧨 Example 2: Dumping Database Tables
Input:
search term: '; DROP TABLE users; --Resulting query:
SELECT * FROM products WHERE name = ''; DROP TABLE users; --';This would delete the users table, causing catastrophic data loss.
🛡️ How to Protect Against SQL Injection
✅ 1. Use Prepared Statements (with Parameterised Queries)
Bad (Vulnerable):
$sql = "SELECT * FROM users WHERE username = '$username'";Good (Safe):
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->execute(['username' => $username]);✅ 2. Use ORM Libraries
Tools like Eloquent (Laravel), Hibernate (Java), or Entity Framework (.NET) abstract raw SQL and safely handle parameters.
✅ 3. Input Validation and Escaping
- Sanitize user input (e.g. using
filter_input()in PHP) - Reject unexpected characters or SQL keywords
✅ 4. Least Privilege Database Access
Ensure database users have only the necessary permissions. For example, the app should not connect as a root user.
✅ 5. Web Application Firewalls (WAF)
Deploy a WAF to detect and block malicious inputs in real time.
✅ 6. Regular Security Testing
- Conduct automated scans (e.g. with OWASP ZAP, sqlmap)
- Perform manual code reviews
🧭 Summary
| Aspect | Details |
|---|---|
| Risk | High: Data theft, unauthorised access, system damage |
| Common Entry Point | Web forms, URLs, cookies |
| Key Defence | Prepared statements, input validation, least privilege |