SQL Injection is a malicious technique where attackers insert or “inject” SQL code into queries through user input, potentially gaining unauthorized access to or control of the database.
It is one of the most common web hacking techniques and can result in serious security vulnerabilities, such as:
- Exposing sensitive data (e.g., usernames, passwords)
- Deleting database tables
- Modifying data
- Executing administrative operations
SQL Injection Syntax
SQL Injection typically happens when input values from the user are directly concatenated into a SQL query, like so:
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
Now if a user inputs:
105 OR 1=1
Then the resulting SQL becomes:
SELECT * FROM Users WHERE UserId = 105 OR 1=1;
1=1
is always true, so this returns all users instead of just one.
This shows how malicious input can completely alter the intent of a SQL query.
SQL Injection Example
Here are common SQL injection patterns:
1. Boolean Injection: OR 1=1
SELECT * FROM Users WHERE UserId = 105 OR 1=1;
This will return all rows because 1=1
is always true.
2. String Injection: ""=""
In login forms, users might enter:
- Username:
" OR ""="
- Password:
" OR ""="
This produces:
SELECT * FROM Users WHERE Name ="" OR ""="" AND Pass ="" OR ""="";
This again returns all users, bypassing authentication.
3. Batched SQL Statements
Some systems allow multiple SQL statements separated by semicolons:
Input:
105; DROP TABLE Suppliers
SQL:
SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers;
Warning: This can delete entire tables!
Note: Batched SQL statements like this may not run in our playground for safety reasons.
SQL Injection Protection
SQL Injection Protection Using SQL Parameters
Instead of directly inserting user input into SQL strings, use parameterized queries.
Example (ASP.NET Razor-style syntax):
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = @0";
db.Execute(txtSQL, txtUserId);
This way, user input is treated as literal values, not executable SQL.
SQL Injection Protection Best Practices
- Always use parameters when working with user input.
- Never concatenate raw input into SQL strings.
- Validate and sanitize input where possible.
- Limit user privileges in the database (e.g., avoid using admin accounts for web apps).
SQL Injection Playground Testing
In our playground environment, you can safely practice SELECT statements and basic WHERE filtering, but note the following:
- Statements like
DROP TABLE
or batched injections using;
will not work (for safety). - Authentication-based injection examples cannot be tested here, since our playground doesn’t simulate web forms.
- You can explore how queries change when altering WHERE clauses like
OR 1=1
.
Example you can try:
This returns all patients, showing how the condition bypasses intended logic.
SELECT * FROM Patients WHERE patient_id = 1 OR 1=1;
