The following characters are affected:
- \x00
- \n
- \r
- \
- '
- "
- \x1a
If successful, the function returns the escaped string. If it fails, false is returned.
grammar
mysql_real_escape_string(string,connection)
parameter | describe |
---|---|
string | Required. Specifies the string to be escaped. |
connection | Optional. Specifies MySQL connection. If not specified, use the previous connection. |
illustrate
This function escapes special characters in string and takes into account the current character set of the connection, so it can be safely used for mysql_query().
Tips and comments
Tip: This function can be used to prevent database attacks.
example
Example 1
<?php
$con = mysql_connect("localhost", "hello", "321");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Code to obtain 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 code
mysql_close($con);
?>
Example 2
Database attack. This example demonstrates what happens if we do not apply the mysql_real_escape_string() function to the username and password:
<?php
$con = mysql_connect("localhost", "hello", "321");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT * FROM users
WHERE user='{$_POST['user']}'
AND password='{$_POST['pwd']}'";
mysql_query($sql);
// Do not check username and password
// It can be anything entered by the user, such as:
$_POST['user'] = 'john';
$_POST['pwd'] = "' OR ''='";
// Some code...
mysql_close($con);
?>
Then SQL queries will become like this:
SELECT * FROM users
WHERE user='john' AND password='' OR ''='' This means that any user can log in without entering a legitimate password.
Example 3
The correct way to prevent database attacks:
<?php
function check_input($value)
{
// Remove the slash
if (get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// If it is not a number, add quotes
if (!is_numeric($value))
{
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
$con = mysql_connect("localhost", "hello", "321");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Conduct 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);
?>