Escape special characters in unescaped_string, taking into account the connection settings of the current character so that it is safe in the place where 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 it fails, it returns false.
Grammar
Mysql_real_escape_string (string,connection)
Parameters |
Description |
String |
Necessary. Specify the string to be escaped. |
Connection |
Optional. Specify the MySQL connection. If not specified, the previous connection is used. |
Description
This function escape special characters in a string and takes into account the current character set of the connection, so it can be used safely for mysql_query ().
Tips and comments
Tip: This function can be used to prevent database attacks.
Example
Example 1
Copy Code code as follows:
<?php
$con = mysql_connect ("localhost", "Hello", "321");
if (! $con)
{
Die (' Could not connect: '. Mysql_error ());
}
Code to obtain username and password
Escape 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 user name and password:
Copy Code code as follows:
<?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 user name and password
Can be anything that the user enters, such as:
$_post[' user ' = ' john ';
$_post[' pwd '] = "' or ' = '";
Some code ...
Mysql_close ($con);
?>
Then the SQL query becomes this way:
SELECT * from users
WHERE user= ' John ' and password= ' OR ' = ' means that any user can log in without entering a valid password.
Example 3
The correct way to prevent database attacks:
Copy Code code as follows:
<?php
function Check_input ($value)
{
Remove Slash
if (GET_MAGIC_QUOTES_GPC ())
{
$value = Stripslashes ($value);
}
Add quotes if not numbers
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 ());
}
To secure the 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);
?>