Jqrp Jqrp - 1 year ago 102
PHP Question

Check if specific value exists in mysql column

I have mysql column called categories. It can contain single or multiple values like this: 1 or 2 or 1,2,3 or 2,12...

I try to get all rows containing value 2.

$query = "SELECT * FROM my_table WHERE categories LIKE '2'";
$rows = mysql_query($query);

This returns row if column only has value 2 but not 1,2,3 or 2,12. How I can get all rows including value 2?

Answer Source

You can use either of the following:

% is a wildcard so it will match 2 or 1,2, etc. Anything on either side of a 2. The problem is it could match 21, 22, etc.

$query = "SELECT * FROM my_table WHERE categories LIKE '%2%'";

Instead you should consider the find_in_set mysql function which expects a comma separated list for the value.

$query = "SELECT * FROM my_table WHERE find_in_set('2', `categories`)";