mysql_real_escape_string
Escapes special characters in a string for use in a SQL statement
Descriptionstringmysql_real_escape_stringstringunescaped_stringresourcelink_identifierunescaped_stringThe string to escapelink_identifier (optional)The mysql connection resource
This function will escape special characters in the
unescaped_string, taking into account the current
character set of the connection so that it is safe to place it in a
mysql_query. If you wish to insert binary data
you must use this function.
mysql_real_escape_string calls MySQL's library function
mysql_escape_string, which prepends backslashes to the following characters:
NULL, \x00, \n,
\r, \, ',
" and \x1a.
Simple mysql_real_escape_string example
]]>
You must always (with few exceptions) use this function to make your data
safe before sending a query to MySQL. If you have
magic_quotes_gpc enabled,
and you are working with data from user input, you must first
stripslashes your data. If your data are form other
sources and you have
magic_quotes_runtime enabled, you also have to
stripslashes your data. If you don't do so, you leave
yourself open to SQL Injection Attacks. Here's an example:
An example SQL Injection Attack
]]>
The query sent to MySQL:
This would allow anyone to log in without a valid password! Using
mysql_real_escape_string around each variable
prevents this.
]]>
The query will now execute correctly, and Injection attacks will no longer work.
mysql_real_escape_string does not escape
% and _. These are wildcards in
MySQL if combined with LIKE, GRANT,
or REVOKE.
See also
mysql_client_encoding,
addslashes,
stripslashes,
the magic_quotes_gpc,
and the
magic_quotes_runtime
directive.