SQL Injection: Definition, Types, and
Live Example
What is SQL Injection?
SQL Injection (SQLi) is a code injection technique that allows an attacker to interfere with
the queries that an application makes to its database. It occurs when user input is
improperly sanitized and directly included in SQL queries. This can allow an attacker to
view, modify, or delete data, and in some cases, even gain control over the server.
Types of SQL Injection
Type Description
Classic (In-band) SQLi Data is extracted using the same channel
(e.g., error messages or query result).
Error-Based SQLi Uses error messages to reveal database
structure.
Union-Based SQLi Uses the UNION SQL operator to combine
results and extract data.
Blind SQLi No output visible; attacker asks true/false
questions and observes behavior.
Time-Based Blind SQLi Uses SQL functions like SLEEP() to infer
data based on response delay.
Out-of-Band SQLi Data is sent to an external source – used
when in-band is not possible.
Live Example of SQL Injection
Scenario: A vulnerable login system
Vulnerable SQL Query:
SELECT * FROM users WHERE username = '$username' AND password = '$password';
User Input:
Username: admin' --
Password: (leave it blank)
Resulting Query:
SELECT * FROM users WHERE username = 'admin' --' AND password = '';
The part after '--' is treated as a comment in SQL, so the password check is ignored. This
allows the attacker to log in without knowing the correct password.
Impact of SQL Injection
• Bypass authentication
• Retrieve sensitive data
• Modify or delete data
• Execute administrative operations (e.g., shutdown database)
• In severe cases: Remote Code Execution (RCE)
How to Prevent SQL Injection
1. Use Prepared Statements / Parameterized Queries
$stmt = $conn->prepare("SELECT * FROM users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
2. Input Validation – Check and sanitize all user inputs.
3. Use ORM frameworks – They handle query-building safely.
4. Least Privilege Principle – Limit DB permissions.
5. Web Application Firewall (WAF) – Helps filter malicious traffic.
Conclusion
SQL Injection is one of the most dangerous vulnerabilities in web applications.
Understanding how it works is essential for developers and cybersecurity professionals.