What is SQL Injection?
SQL injection is a code injection technique, used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker) – Wikipedia
SQL injection errors occur when:
1. Data enters a program from an untrusted source.
2. The data is used to dynamically construct a SQL query.
Now, let us see some of the practical Scenario of SQL injection. For example consider an application which has a login page, it is possible that the application uses a dynamic SQL Statement as below.
SELECT * FROM Employee WHERE Employee_Name = 'strEmployeeName' AND Password = 'strPassword';
This statement is expected to return at least a single row with the employee details from the Employee table as the result set when there is a row with the employee name and password entered in the SQL statement.
If the attacker would enter Gokul as the strEmployeeName (in the textbox for employee name) and Krish as strPassword (in the textbox for password), the above SQL statement would become:
SELECT * FROM Employee WHERE Employee_Name = 'Gokul' AND Password = 'Krish';
If an attacker enters the string ‘Gokul’ OR ‘a’=’a’ for strEmployeeName, and ‘Krish’ OR ‘a’=’a’ for strPassword then the query becomes the following:
SELECT * FROM Employee WHERE Employee_Name = 'Gokul' OR 'a'='a'
AND Password = 'Krish' OR 'a'='a';
Since ‘a’=’a’ condition is always true, the result set would consist of all the rows in the Employee table. The application could allow the attacker to log in as the first employee in the Employee table.
If the attacker would enter ‘Gokul’; DROP table Employee; as strEmployeeName and anything as strPassword, the SQL statement would become like the one below.
SELECT * FROM Employee WHERE Employee_Name = 'Gokul';
DROP table Employee; AND Password = 'Krish'
This statement could cause the table Employee to be permanently deleted from the database.
So inorder to avoid SQL inject errors it is better to use prepare statement instead of normal statement.