When SQL is used to display data on a web page, it is common to let web users input their own search values.
Since SQL statements are text only, it is easy, with a little piece of computer code, to dynamically change SQL statements to provide the user with selected data:
txtUserId = getRequestString("UserId"); txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
Let’s say that the original purpose of the code was to create an SQL statement to select a user with a given user id.
If there is nothing to prevent a user from entering “wrong” input, the user can enter some “smart” input like this:
105 or 1=1
SELECT * FROM Users WHERE UserId = 105 or 1=1
The SQL above is valid. It will return all rows from the table Users, since WHERE 1=1 is always true.
Does the example above seem dangerous? What if the Users table contains names and passwords?
The SQL statement above is much the same as this:
SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1
A smart hacker might get access to all the user names and passwords in a database by simply inserting 105 or 1=1 into the input box.
SQL injection errors occur when:
- Data enters a program from an untrusted source.
- The data used to dynamically construct a SQL query.