php mysql_real_escape_string Function usage and example tutorial
- 2020-10-23 20:03:35
- OfStack
The following characters are affected:
\x00 \n \r \ ' " \x1aIf successful, the function returns the escaped string. If this fails, false is returned.
grammar
mysql_real_escape_string(string,connection)
parameter
describe
string
A necessity. Specifies the string to escape.
connection
Optional. Specify the MySQL connection. If not specified, the previous connection is used.
instructions
This function escapes the special characters in string and is safe for use with mysql_query() considering the current character set of the connection.
Hints and comments
Tip: You can use this function to prevent database attacks.
example
Example 1
<?php
$con = mysql_connect("localhost", "hello", "321");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// The code to get the username and password
// Escape user name and password so that in SQL The use of
$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 demonstrates what happens if we don't apply the mysql_real_escape_string() function to the user name 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 the user enters, such as:
$_POST['user'] = 'john';
$_POST['pwd'] = "' OR ''='";
// 1 Some of the code ...
mysql_close($con);
?>
The SQL query would look like this:
SELECT * FROM users
WHERE user='john' AND =' OR '=' OR '=' OR '=' OR '=' OR '=' user '=' john' =' OR '
Example 3
The right way to prevent database attacks:
<?php
function check_input($value)
{
// Remove the slashes
if (get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// If it's not a number, put it in 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());
}
// Carry on safe 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);
?>