2

I have a string array in PHP called groups. The array looks something like this based on user input: groups[All, Sales].

Example: (UPDATED TABLE SCHEMA)

groups[] = ['Sales', 'All']

            ANNOUNCEMENT
 |description|masterID|  groupName   |
=======================================
 | hello     | 1      | All, Final,  |
 | greetings | 2      | Sales, All,  |
 | demo      | 3      | Final,       |

So from above table it should only return "hello" and "greetings" as output because groups[] has Sales and All as row 1 has All and row 2 has both. Please help. I am an amateur in SQL and PHP both.

My current try:

SELECT * FROM announcement WHERE groupName REGEXP '(Sales | All)'

Output:

No rows affected
3
  • 3
    NEVER store comma separated values in database. To retrieve them you'll need a full text search through LIKE "%Final%". Commented May 4, 2013 at 12:47
  • 2
    I would suggest to normalize your database. Create a new table with group names and have another table with masterID and groupId. That would make your life a lot easier going forward as well. Commented May 4, 2013 at 12:48
  • Thanks for all your suggestions, but this is what I have to work with. Can't change it otherwise I would have easily solved this issue. Can you show me a way to work with this? Commented May 4, 2013 at 12:51

2 Answers 2

3
  1. I guess, your groups should really be in string format: groups[] = ['Final', 'All', 'Test'].

  2. This $search = implode('|', $groups) will produce a string Final|All|Test.

  3. Now you need to put this string into your query to search by either or the words. So, this is WHERE groupName REGEXP '({$search})'. Don't forget about quotes inside the query and so that they don't clash with quotes you put your whole query in.

Sign up to request clarification or add additional context in comments.

2 Comments

I changed my table schema to make it: |description|masterID|groupName|. Please check my updated question above.
The only error was REGEXP '($search)'. It should have been a rounded bracket. It works now :)
1

MySQL does Perl-like regular expressions. Construct a query similar to this:

SELECT description
  FROM announcement NATURAL JOIN master
 WHERE groupName REGEXP '\\b(Final|All|Test)\\b';

3 Comments

But how do I get each group array element in between REGEXP?
I left that as an exercise -- but something like $query = 'SELECT ... REGEXP \'\\\\b(' . implode('|', $groups) . ')\\\\b\'' would work.
I am pretty amateur. Although I am searching it on google on how to do it, if you could just get me through, I would be grateful to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.