Definition and usage
The mysql_real_escape_string () function escapes special characters in strings used in SQL statements.
The following characters are affected:
\x00
\ n
\ r
\
'
"
\x1a
If successful, the function returns the escaped string. If it fails, it returns false.
Grammar
Mysql_real_escape_string (string,connection)
Parameter description
string is required. Specifies the string to be escaped.
Connection is optional. Specify MySQL connection. If not specified, the previous connection is used.
Description
This function escapes the special characters in the string and takes into account the current character set of the connection, so it can be used safely for mysql_query ().
Hints and Notes
Tip: You can use this function to prevent database attacks.
Example
Example 1
$con = mysql_connect ("localhost", "Hello", "321");
if (! $con)
{
Die (' Could not connect: '. Mysql_error ());
}
Code to get the user name and password
To escape the user name 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 attacks. This example shows what happens if we do not apply the mysql_real_escape_string () function to the username and password:
$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 the user name and password//can be any content entered by the user, such as:
$_post[' user '] = ' John ';
$_post[' pwd '] = "' OR ' = '";
Some code ...
Mysql_close ($con);
?>
Then the SQL query will be 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
The right way to prevent database attacks:
function Check_input ($value)
{
Slash slash removal
if (GET_MAGIC_QUOTES_GPC ())
{
$value = Stripslashes ($value);
}
If it's not a number, enclose it.
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 ());
}
Make 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);
?>
Author "The Other Shore"
http://www.bkjia.com/PHPjc/478619.html www.bkjia.com true http://www.bkjia.com/PHPjc/478619.html techarticle define and use the mysql_real_escape_string () function to escape special characters in the string used in the SQL statement. The following characters are affected: \x00 \ r \ \x1a If successful, the function returns ...