SQL Injection – Complete Notes
Example Database Table
Before understanding SQL Injection, here is an example of how a database table looks.
Table name: users
user_id user password
1 admin 5f4dcc3b
2 john e99a18c4
3 alice 202cb962
Each row represents one user. Columns store different types of data.
What is SQL Injection
SQL Injection is a vulnerability where user input is directly inserted into an SQL query
without proper validation. Attackers can manipulate the query logic to access, modify, or
delete data.
Main Types of SQL Injection
1. Boolean-Based SQL Injection
This type uses TRUE or FALSE conditions to manipulate results.
Example:
SELECT * FROM users WHERE user_id = '1' OR '1'='1';
Because '1'='1' is always true, all rows are returned.
2. Error-Based SQL Injection
This type forces database errors to leak information such as table names or database
version.
Example:
AND updatexml(1, concat(0x7e, version()), 1);
3. UNION-Based SQL Injection
UNION-based SQL Injection combines results from another query.
Example:
UNION SELECT user, password FROM users;
This allows attackers to extract sensitive data.
4. Blind SQL Injection
Blind SQL Injection occurs when no data is shown, but behavior changes.
Boolean Blind Example:
AND 1=1;
AND 1=2;
Time-Based Example:
AND SLEEP(5);
5. Out-of-Band SQL Injection
Data is sent outside the application using DNS or HTTP requests. This is used when no
response is visible.
6. Second-Order SQL Injection
The payload is stored in the database and executed later when another query uses it.
7. Stacked Queries
Multiple SQL queries are executed in one input.
Example:
; DROP TABLE users;
How SQL Injection is Prevented
1. Use prepared statements.
2. Validate and sanitize user input.
3. Use least-privilege database accounts.
4. Disable detailed SQL error messages.