SQL Injection

SQL Injection

SQL injection is a code injection technique that might destroy your database. It is one of the most common web hacking techniques.

SQL injection is the placement of malicious code in SQL statements, via web page input.


How it Works

Imagine a web application has an input field for a User ID. The backend code might construct a query like this:

txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;

A legitimate user would enter their ID, say 105, and the query would become: SELECT * FROM Users WHERE UserId = 105;

However, a malicious user could enter 105 OR 1=1. The resulting SQL query would be: SELECT * FROM Users WHERE UserId = 105 OR 1=1;

Since 1=1 is always true, this query would return all rows from the Users table, exposing all user data.

Worse, a hacker could input 105; DROP TABLE Users; to delete the entire table.


How to Prevent SQL Injection

To protect a web site from SQL injection, you need to use SQL parameters or prepared statements.

Prepared statements are a way of pre-compiling an SQL statement so that all you need to do is supply the parameters for it to be executed. The database engine does not mix the query logic with the parameter values, making it immune to injection attacks.

Here is an example using parameters in C# / ASP.NET:

txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Users WHERE UserId = @0";
db.Execute(sql, txtUserId);

By using parameters, the database treats the input 105 OR 1=1 as a single, literal string, not as part of the SQL logic. The query fails safely because there is no user with that exact ID.