Bruno
Bruno

Reputation: 95

Check if a string is in a MySQL field value

I have a DB field called 'colors' where I store favourite colors from people. These are selected from a multi-select field and I store them all in one field. I use PHP to get all the values in one field using:

$lookfor = implode(",", $looking_for);

What's the best way to search for a string within a field that contains values in the format red,blue,yellow....

Since the users will use the same multi-select box I still need to access the values in this format. I tried using

SELECT * 
  FROM users 
 WHERE users_looking_for LIKE '%$lookfor%'

But this won't work if my values are not store in the same order as they are searched.

Upvotes: 1

Views: 3296

Answers (4)

OMG Ponies
OMG Ponies

Reputation: 332731

Short term solution

Use the FIND_IN_SET function:

$query = sprintf("SELECT u.* 
                    FROM USERS u
                   WHERE FIND_IN_SET('%s', u.users_looking_for) > 0", 
                  mysql_real_escape_string($lookfor));

If you want to search for more than one lookfor value, you will need to add additional FIND_IN_SET checks:

WHERE FIND_IN_SET('value1', u.users_looking_for) > 0
  AND FIND_IN_SET('value2', u.users_looking_for) > 0

Long Term Solution

Do not store denormalized data - use a many-to-many table setup:

PEOPLE

  • people_id (primary key)

COLORS

  • color_id (primary key)

PEOPLE_COLORS

  • people_id (primary key, foreign key to PEOPLE.people_id)
  • color_id (primary key, foreign key to COLORS.color_id)

Upvotes: 8

judda
judda

Reputation: 3972

I would suggest that instead of using a VARCHAR field to hold the list of selected colours, you move to more of a relational approach, where each colour for each user is listed. That way when you do your query you are able to say where it is IN a set of values which are their selections.

Upvotes: 0

Intrepidd
Intrepidd

Reputation: 20938

You should use a table user_colors with two fields : "user_id" and "color"

This would be much easier to search for values.

example :

SELECT * FROM user_colors WHERE color='red' OR color='blue';

Upvotes: 0

magma
magma

Reputation: 8530

but this won't work if my valyes are not store in the same order as they are searched.

Sort them before storing, and sort them before searching.

Upvotes: 0

Related Questions