Escape special characters in unescaped_string, taking into account the current character's connection settings so that it is safe in place in mysql_query() it. If binary data is to be inserted, this function must be used
The following characters are affected:
If successful, the function returns the escaped string. If failed, returns false.
mysql_real_escape_string(string,connection)
参数 | 描述 |
---|---|
string | 必需。规定要转义的字符串。 |
connection | 可选。规定 MySQL 连接。如果未规定,则使用上一个连接。 |
Description
This function escapes special characters in a string and takes into account the current character set of the connection, so it is safe to use with mysql_query().
Tips and Notes
Tip: You can use this function to prevent database attacks.
Example
Example 1
// Code to get username and password
// Escape username and password for use in SQL
$user = mysql_real_escape_string($user);
$pwd = mysql_real_escape_string($pwd);
$sql = "SELECT * FROM users WHERE
user='" . $user . "' AND password='" . $pwd . "'"
//More codes
mysql_close($con);
?>
Example 2
Database attack. This example shows what happens if we don't apply the mysql_real_escape_string() function to the username and password:
$sql = "SELECT * FROM users
WHERE user='{$_POST['user']}'
AND password='{$_POST['pwd']}'";
mysql_query($sql);
// Does not check username and password
// Can be anything entered by the user, such as:
$_POST['user'] = 'john';
$_POST['pwd'] = "' OR ''='";
// Some code...
mysql_close($con);
?>
Then the SQL query will look like this:
SELECT * FROM users
WHERE user='john' AND password='' OR ''='' This means that any user can log in without entering a valid password.
Example 3
Correct way to prevent database attacks:
$con = mysql_connect("localhost", "hello", "321");
if (!$con)
{
die('Could not connect: ' . mysql_error()) ;
}
// Perform secure SQL
$user = check_input($_POST['user']);
$pwd = check_input($_POST['pwd']);
$sql = " SELECT * FROM users WHERE
user=$user AND password=$pwd";
mysql_query($sql);
mysql_close($con);
?>