The mysql_real_escape_string () function is used to escape special characters in the strings used in SQL statements in unescaped_string. Considering the connection settings of the current character, it is safe in mysql_query () it. If binary data is to be inserted, this function must be used.
The following characters are affected:
- \ X00
- \ N
- \ R
- \
- '
- "
- \ X1a
If yes, the function returns the escaped string. If it fails, false is returned.
Syntax
mysql_real_escape_string(string,connection)
Parameters |
Description |
String |
Required. Specifies the string to be escaped. |
Connection |
Optional. MySQL connection is required. If not specified, use the previous connection. |
Description
This function escapes special characters in string and considers the connected current character set. Therefore, it can be safely used for mysql_query ().
Tips and comments
Tip: you can use this function to prevent database attacks.
Example
Example 1
The code is as follows:
$ Con= mysql_connect ("localhost", "hello", "321 ");
If (! $ Con)
{
Die ('could not connect: '. mysql_error ());
}
// Code for obtaining the user name and password
// Escape the 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 attacks. This example shows what will happen if we do not apply the mysql_real_escape_string () function to the user name and password:
The code is as follows:
$ 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
// Any content entered by the user, for example:
$ _ POST ['user'] = 'John ';
$ _ POST ['pwd'] = "'OR'' = '";
// Some code...
Mysql_close ($ con );
?>
The SQL query will be like this:
SELECT * FROM users
WHERE user = 'John' AND password = ''OR'' = '', which means that any user can log in without entering a valid password.
Example 3
The correct method to prevent database attacks:
The code is as follows:
Function check_input ($ value)
{
// Remove the slash
If (get_magic_quotes_gpc ())
{
$ Value = stripslashes ($ value );
}
// If it is not a number, enclose it with quotation marks.
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 ());
}
// Perform a safe SQL statement
$ 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 );
?>