Home > Backend Development > PHP Tutorial > php mysql_real_escape_string() function_PHP tutorial

php mysql_real_escape_string() function_PHP tutorial

WBOY
Release: 2016-07-13 17:05:36
Original
876 people have browsed it

mysql tutorial_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 failed, returns false.

Grammar
mysql_real_escape_string(string,connection) parameter description
string required. Specifies the string to be escaped.
connection is optional. Specifies the MySQL connection. If not specified, the previous connection is used.
Example

function opendatabase ($host,$user,$pass) {
Try {
If ($db = mysql_connect ($host,$user,$pass)){
         return $db;
} else {
          throw new exception ("Sorry, could not connect to mysql.");
}
} catch (exception $e) {
echo $e->getmessage ();
}
}

function selectdb ($whichdb, $db){
Try {
If (!mysql_select_db ($whichdb,$db)){
throw new exception ("Sorry, database could not be opened.");
}
} catch (exception $e) {
echo $e->getmessage();
}
}
function closedatabase ($db){
Mysql_close ($db);
}
$db = opendatabase ("localhost","root","");
selectdb ("mydatabase",$db);
$_POST['user'] = "myname";
$_POST['pass'] = "mypassword";

function validatelogin ($user,$pass){
Mysql_real_escape_string ($user);
Mysql_real_escape_string ($pass);
$thequery = "SELECT * FROM userlogin WHERE username='$user' AND password='$pass'";
If ($aquery = mysql_query ($thequery)){
If (mysql_num_rows ($aquery) > 0){
        return true;
} else {
         return false;
}
} else {
echo mysql_error();
}
}

if (validatelogin ($_POST['user'],$_POST['pass'])){
echo "You have successfully logged in.";
} else {
echo "Sorry, you have an incorrect username and/or password.";
}

closedatabase ($db);

?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/630752.htmlTechArticlemysql tutorial_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...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template