Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding exact value from a comma separated string in PHP MySQL

Tags:

regex

php

mysql

I have a product table which contains a field called 'categories' to save product related category ids as comma separated values. I am using regexp to search products from a category.

Assume there is record containing 4,24,1,31 my expression is,

..WHERE categories REGEXP ',?4,?'

but this returns both product of category 4 and 24

I just need to display only category 4.

Am I missing something?

like image 882
vinu Avatar asked Sep 24 '12 06:09

vinu


People also ask

How do I find comma separated values in MySQL?

MySQL has an inbuilt function called FIND_IN_SET which will search for values within a comma separated values. It basically returns the index position of the first parameter within the second parameter. This can be alternatively used to replace the IN clause. WHERE FIND_IN_SET (item_description,'Mobile,laptop');

How do I get row values as comma separated by a query in MySQL?

In MySQL, you can return your query results as a comma separated list by using the GROUP_CONCAT() function. The GROUP_CONCAT() function was built specifically for the purpose of concatenating a query's result set into a list separated by either a comma, or a delimiter of your choice.

How can use comma separated string in PHP?

The task is to split the given string with comma delimiter and store the result in an array. Use explode() or preg_split() function to split the string in php with given delimiter. PHP | explode() Function: The explode() function is an inbuilt function in PHP which is used to split a string in different strings.


1 Answers

Use

WHERE categories REGEXP "(^|,)4(,|$)"

This matches 4 if surrounded by commas or at the start/end of the string.

In your present version, both commas are entirely optional, so the 4 in 24 matches.

like image 84
Tim Pietzcker Avatar answered Sep 27 '22 17:09

Tim Pietzcker