PHP mysql_real_escape_string () function
PHP MySQL function
Definitions and Usage
The mysql_real_escape_string () function escapes special characters in the string used in the SQL statement.
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)
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
Mysql_real_escape_string ($user);
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:
Then the SQL query becomes this way:
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 correct way to prevent database attacks:
Stripslashes ($value);
If it is not a number, add the quote if
(!is_numeric ($value))
{
mysql_real_escape_string($value)
. "'";
}
return $value;
}
$con = mysql_connect ("localhost", "Hello", "321");
if (! $con)
{
die (' Could not connect: '. Mysql_error ());
}
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);
? >