Tuesday, 28 December 2021

MYSQL LIKE Query , Underscore and Mod symbols are wildcare, need to be escaped, PHP string replace with array

 https://stackoverflow.com/questions/19588455/why-does-using-an-underscore-character-in-a-like-filter-give-me-all-the-results


The '_' and '%' are wildcards in a LIKE operated statement in SQL.

The _ character looks for a presence of (any) one single character. If you search by columnName LIKE '_abc', it will give you result with rows having 'aabc''xabc''1abc''#abc' but NOT 'abc''abcc''xabcd' and so on.

The '%' character is used for matching 0 or more number of characters. That means, if you search by columnName LIKE '%abc', it will give you result with having 'abc''aabc''xyzabc' and so on, but no 'xyzabcd''xabcdd' and any other string that does not end with 'abc'.

In your case you have searched by '%_%'. This will give all the rows with that column having one or more characters, that means any characters, as its value. This is why you are getting all the rows even though there is no _ in your column values.



Solution 


WHERE mycolumn LIKE '%\_%' ESCAPE '\'


PHP ESCAPE Underscore and Mod
https://stackoverflow.com/questions/15424102/search-with-in-mysql-query-like

$key = str_replace(array('%', '_'), array('\%', '\_'), $key);

No comments:

Post a Comment