Escaping Backslashes in MySQL: Usage in WHERE and LIKE Clauses
Consider the following query that searches for a title containing a backslash:
(SELECT * FROM `titles` WHERE title = 'test\') UNION ALL (SELECT * FROM `titles` WHERE title LIKE 'test\\')
The output shows that the backslash is not escaped in the WHERE clause. However, an additional backslash is required for the LIKE clause.
Why the Difference?
In MySQL, backslashes () function as escape characters in LIKE by default. According to the MySQL manual for LIKE:
"Because MySQL uses C escape syntax in strings... you must double any '' that you use in LIKE strings. For example, to search for 'n', specify it as 'n'. To search for '', specify it as '\'; this is because the backslashes are stripped once by the parser and again when the pattern match is made, leaving a single backslash to be matched against."
Escaping Backslashes
However, MySQL provides the ability to change the escape character using the ESCAPE keyword. For instance, the following query would use a pipe character (|) as the escape character:
SELECT * FROM `titles` WHERE title LIKE 'test\' ESCAPE '|'
With this query, only a single backslash is required in the LIKE clause, as the pipe character will be used for escaping.
The above is the detailed content of Why Do MySQL's WHERE and LIKE Clauses Require Different Backslash Escaping?. For more information, please follow other related articles on the PHP Chinese website!