PHP mysql_real_escape_string () function
PHP MySQL Functions
Definition and usage
The mysql_real_escape_string () function escapes 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)
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 willStringThe special character escape in, and considering the connected Current Character Set, can be safely used for mysql_query ().
Tips and comments
Tip: You can use this function to prevent database attacks.
Example 1
Mysql_real_escape_string ($ user); $ Pwd =mysql_real_escape_string($pwd)
; $ SQL = "SELECT * FROM users WHEREuser = '". $ 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 SQL query will be like this:
SELECT * FROM usersWHERE user='john' AND password='' OR ''=''
This means that any user can log on without entering a valid password.
Example 3
The correct method to prevent database attacks:
Stripslashes ($ value);} // If it is not a number, enclose the quotation mark 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 security SQL $ user = check_input ($ _ POST ['user']); $ pwd = check_input ($ _ POST ['pwd']); $ SQL = "SELECT * FROM users WHEREuser = $ user AND password = $ pwd"; mysql_query ($ SQL ); mysql_close ($ con);?>