Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, MySQL: mysql substitute for php in_array function

Tags:

php

search

mysql

Say if I have an array and I want to check if an element is a part of that array, I can go ahead and use in_array( needle, haystack ) to determine the results. I am trying to see the PHP equivalent of this for my purpose. Now you might have an instant answer for me and you might be tempted to say "Use IN". Yes, I can use IN, but that's not fetching the desired results. Let me explain with an example:

I have a column called "pets" in DB table. For a record, it has a value: Cat, dog, Camel (Yes, the column data is a comma separated value). Consider that this row has an id of 1.

Now I have a form where I can enter the value in the form input and use that value check against the value in the DB. So say I enter the following comma separated value in the form input: CAT, camel (yes, CAT is uppercase & intentional as some users tend to enter it that way).

Now when I enter the above info in the form input and submit, I can collect the POST'ed info and use the following query:

$search = $_POST['pets'];
$sql = "SELECT id FROM table WHERE pets IN ('$search') "; 
  1. The above query is not fetching me the row that already exists in the DB (remember the record which has Cat, dog, Camel as the value for the pets column?). I am trying to get the records to act as a superset and the values from the form input as subsets. So in this case I am expecting the id value to show up as the values exist in the column, but this is not happending.

  2. Now say if I enter just CAT as the form input and perform the search, it should show me the ID 1 row.

  3. Now say if I enter just camel, cAT as the form input and perform the search, it should show me the ID 1 row.

How can I achieve the above?

Thank you.

like image 476
Devner Avatar asked Jan 21 '23 23:01

Devner


1 Answers

The function you're looking for is find_in_set:

 select * from ... where find_in_set($word, pets)

for multi-word queries you'll need to test each word and AND (or OR) the tests:

  where find_in_set($word1, pets) AND find_in_set($word2, pets) etc 
like image 92
user187291 Avatar answered Jan 31 '23 14:01

user187291