MYSQL Injection

MySQL Injection can provide an attacker with unauthorized access to sensitive data including, customer data, password and other sensitive information.

MySQL injection is an application security weakness that allows attackers to control an application’s database.Also on the other hand, MySQL injection is a code injection technique that might destroy your database.

sql injection example:

Below is a fatch user name from students table and a bad user trying to use SQL Injection.

MySQL & PHP Code:

$name_evil = “‘; DELETE FROM students WHERE 1 or username = ‘”;

// our MySQL query builder really should check for injection
$query_evil = “SELECT * FROM students WHERE username = ‘$name_evil'”;

// the new evil injection query would include a DELETE statement
echo “Injection: ” . $query_evil;

Display:

SELECT * FROM students WHERE username = ‘ ‘; DELETE FROM students WHERE 1 or username = ‘ ‘;

If you were run this query, then the injected DELETE statement would completely empty your “students” table. Now that you know this is a problem, how can you prevent it?

Preventing MySQL Injection – mysql_real_escape_string()

You can handle all escape characters smartly in scripting languages like PERL and PHP. The MySQL extension for PHP provides the function mysql_real_escape_string() to escape input characters that are special to MySQL.

MySQL & PHP Code:

$name_evil = “‘; DELETE FROM students WHERE 1 or username = ‘”;

$name_evil = mysql_real_escape_string($name_evil);

$query_evil = “SELECT * FROM students WHERE username = ‘$name_evil'”;
echo “Escaped Evil Injection:
” . $query_evil;

Display:

Escaped Bad Injection:
SELECT * FROM students WHERE username = ‘\’ OR 1\”;

Escaped Evil Injection:
SELECT * FROM students WHERE username = ‘\’; DELETE FROM students WHERE 1 or username = \”;