Mysql tutorial _ real_escape_string () function escape special characters in strings used in SQL statements.
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) parameter description
String is required. Specifies the string to be escaped.
Connection is optional. MySQL connection is required. If not specified, use the previous connection.
Instance
<? Php tutorial
Function opendatabase ($ host, $ user, $ pass ){
Try {
If ($ db = mysql_connect ($ host, $ user, $ pass )){
Return $ db;
} Else {
Throw new exception ("Sorry, cocould 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 cocould 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 );
?>