This will teach how to prevent injecting PHP and MySQL to help you protect your scripts and MySQL statements.

What is SQL injection?

SQL injection is when someone inserted MySQL statement is not running on your knowledge database behavior. Injection usually happens when you ask a user input, as their name instead of a name, they give you a MySQL statement that you run on your database when unknowingly.

Examples of SQL injection

$name = $_POST['username'];
$query = "SELECT * FROM `tbl_name` WHERE `name` = '$name' ";

As you can see the value the user enters a username variable will get assigned to the variable $ name, and then directly into the SQL statement URL. This means that it is possible for the user to edit the SQL statement.

$name = "admin' OR 1=1 -- ";
$query = "SELECT * FROM `tbl_name` WHERE `name` = '$name' ";

Then, SQL statements, SQL database will receive the following:

SELECT * FROM `tbl_name` WHERE `name` = 'admin' OR 1=1 --'

This is a valid SQL, rather than return the user data, all data in the statement table ‘table_name` returned. It’s not anybody want their Web applications. This tutorial will show you how to prevent such vulnerabilities.

So, how to prevent injection MYSQL in PHP a simple way?

This problem has been known for some time, PHP has a special function to prevent these attacks. All you need to do is use the function mysql_real_escape_string ().

What mysql_real_escape_string do is take will use the MySQL query and returns all SQL injection attempt to escape the same character in the string. Basically, it will replace those troublesome quotes (‘) and a MySQL user may secure alternative escape quotes \ input. ”

Let’s try to learn from our previous two injection attacks this feature to see how it works.

$name = mysql_real_escape_string($_POST['username']);
$query = "SELECT * FROM `tbl_name` WHERE `name` = '$name' ";

Let’s create a proper function for it, you can call it by any name, I am here it will be named “MRES”.

function mres($var){
    if (get_magic_quotes_gpc()){
        $var = stripslashes(trim($var));
    }
    return mysql_real_escape_string(trim($var));
}

So you can not simply use this feature.

$name = mres($_POST['username']);
$query = "SELECT * FROM `tbl_name` WHERE `name` = '$name' ";