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 successful, the function returns the escaped string. If it fails, it returns false.
Grammar
Mysql_real_escape_string (string,connection)
| Parameters |
Description |
| String |
Necessary. Specifies the string to be escaped. |
| Connection |
Optional. Specify MySQL connection. If not specified, the previous connection is used. |
Description
This function escapes the special characters in the string and takes into account the current character set of the connection, so it can be used safely for mysql_query ().
Hints and Notes
tip: You can use this function to prevent database attacks.
Example
Example 1
Example 2
Database attacks. This example shows what happens if we do not apply the mysql_real_escape_string () function to the username and password:
Then the SQL query will be like this:
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 right way to prevent database attacks: