简体   繁体   中英

When to use mysql_real_escape_string()

When is the correct time to use mysql_real_escape_string?

Should I be using it when I use isset(mysql_escape_string($_GET['param'])),

Should I be using it when I use $foo = mysql_real_escape_string($_GET['bar']);

Thanks

You need to call this function when building SQL queries with string literals.
You should not call it anywhere else.

The point of calling this function is to prevent you from executing SQL like SELECT * FROM Students WHERE Name = 'Robert'); DROP TABLE Students;--' SELECT * FROM Students WHERE Name = 'Robert'); DROP TABLE Students;--' .
mysql_real_escape_string will escape the ' character so that the evil string is treated entirely as a string.

You should use it whenever you don't trust the data you are inserting in a mysql query to prevent sql injections. For example all user forms data. In your first example: no. Second example: yes, if you are going to use the $foo variable in a query.

You should use it whenever you are inserting data into a database query (POST/GET data), but not if you just need to check the data.

You use mysql_real_escape_string whenever you have input from a user that you want to use in a query.

Here's how to use it:

$user = mysql_real_escape_string('$_GET['user']);
$password = MD5($user.$_GET['password']);
$query = "SELECT * FROM users WHERE user = '$user' AND password = '$password' ";
//the quotes are vital  !!                 ^     ^  or you will not be safe!

Here's example code that doesn't work:

在此处输入图像描述 Broken code

$user = mysql_real_escape_string('$_GET['user']);
$password = MD5($user.$_GET['password']);
$query = "SELECT * FROM users WHERE user = $user AND password = '$password' ";

In the example I can login into your system by entering any password whatsoever and
user or (1=1) -- . This will make the query to read:

SELECT * FROM users WHERE user = user or (1=1) --  AND password = '$password

And will approve all logins because the password never gets checked.

When using mysql_query, you can only ever execute one SQL-statement at a time, so:

$query = "SELECT * FROM a; DELETE FROM a WHERE (1=1)"
mysql_query($query);

Will result in an error, because cannot be a part after the ;.

This code however will work:

Danger

$query = "SELECT * FROM a; DELETE FROM a WHERE (1=1)"
mysqli_query($query);

Because the improved mysqli_query does allow two or more statements to be executed in one go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM