====== SQL Injection - Example attacks - Basic SQL Injection attack ======
===== Basic SQLi attack =====
If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example:
$unsafe_variable = $_POST['user_input'];
mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");
That's because the user can input something like
value'); DROP TABLE table;--
and the query becomes:
INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')
This would drop the table, i.e. not what is likely intended to be done.
===== Another example =====
Code to do an insert into the database could also be vulnerable.
$sql = "INSERT INTO Students (Name) VALUES ('" . $studentName . "');";
execute_sql($sql);
The first line creates a string containing an SQL INSERT statement. The content of the $studentName variable is glued into the SQL statement. The second line sends the resulting SQL statement to the database. The pitfall of this code is that outside data, in this case the content of $studentName, becomes part of the SQL statement.
First let's see what the SQL statement looks like if we insert a student named John:
INSERT INTO Students (Name) VALUES ('John');
This does exactly what we want: it inserts John into the Students table.
Now we insert some injection code by setting $studentName to **Robert'); DROP TABLE Students;--**. The SQL statement becomes:
INSERT INTO Students (Name) VALUES ('Robert'); DROP TABLE Students;--');
This inserts Robert into the Students table. However, the INSERT statement is now followed by a **DROP TABLE** statement which removes the entire Students table. Ouch!