MySQL like character escaping pit encountered inquiry

Recently encountered a problem when MySQL query like, when obviously the same string, but not like the results, after many back to find information, and finally found a string escaped the problem, and the MySQL LIKE escape and ordinary characters different.

First look at a test:

1

2

3

4

5

6

7

mysql> SET @a='\';SELECT @a,@a LIKE '\\';

 

+----+----------------+

| @a | @a LIKE '\\' |

+----+----------------+

|   |              1 |

+----+----------------+

It can be seen "\\" escape into the in LIKE "" escaped LIKE escape character string and usually use a little different.

I checked the official documents, the interpretation of the escape character:

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.

mysql own parser escaped once, and then the pattern of the previous LIKE result of a sub-righteousness.

That is the example of "\\" for the first time escaped as "\", the second is the "."

Let's look at a character escape mysql test

1

2

3

4

5

6

7

mysql> SELECT '%','_';

+----+----+

| % | _ |

+----+----+

| % | _ |

+----+----+

1 row in set

Oh, nothing escapes (such as "x" escaped as "x", "b" is a fallback character), is not escaping "%" and "_." The LIKE, have escaped. I'm afraid MYSQL purpose of doing so is for compatibility LIKE it.

Under summary, when LIKE escape string, a total of twice, the first time no escaping "%" and "_", the second time all escaped. Escape special characters can be found in http://dev.mysql.com/doc/refman/5.1/en/string-literals.html#character-escape-sequences

LIKE escape can be seen as first replace "\\" to "", the rest of the string "\" escape, and then the rest of the string, "" escape. Do not usually meet, "\", a special analytical LIKE is imperceptible.

PHP version like special character filtering

1

2

3

function likeEscape($str) {

    return strtr($strarray('%'=>'\%''_'=>'\_''\'=>'\\\\'));

}

Note that the last double backslash backslash turned into eight, in fact, 1 turn 4, but need to convert a string in PHP, a little around here, you think about it, there are problems you can leave a message

发布了29 篇原创文章 · 获赞 9 · 访问量 3万+

Guess you like

Origin blog.csdn.net/HAOXUAN168/article/details/104087348