How to select database MySQL when use array compare with array ?
$num = array("1","6","20");
TABLE : test_db
___________________________
| id | number |
| 1 | "1","2","3","4","5" |
| 2 | "7","8","9" |
| 3 | "10","20","30" |
| 4 | "6","8","20" |
I want to select data from table: test_db
like
select * From test_db WHERE find_in_set($num, number)......
After finished I will get result id 1
, 3
AND 4
Because in id 1 have "1"
and in id 3 have "20"
and in id 4 have "6"
and "20"
How can I select from database.
THANK YOU.
Your DB schema is pretty bad and in addition you are saving comma-separated values using double quote. You should normalize the table and make it one to many relation. However in the current case you need to generate the query dynamically since find_in_set
could be used to search only one value from a set. Here is a way you can try
$num = array("1","6","20");
$qry = "select * from test_db";
$i = 1 ;
if(is_array($num) && count($num) > 0 ){
$qry .= " where ";
foreach($num as $num){
if($i == 1 ){
$qry .= " find_in_set(".$num.",replace(number,'\"','') ) ";
}else{
$qry .= " OR find_in_set(".$num.",replace(number,'\"','') ) ";
}
$i++;
}
}
// Finally execute the query in variable $qry