简体   繁体   中英

Why does my find_in_set match for a single value only and not for comma separated values?

I have a problem in matching with find_in_set ; it does not matches for multiple comma separated values.

Below is what i have tried

$skills = array('php','html','laravel','nodejs');

$skills = implode(',', $skills);

$sql = "SELECT * FROM jobs_posted_by_employer WHERE FIND_IN_SET(skills, :array)";

$stmt = $db->prepare($sql);

$stmt->bindParam('array', $skills);

For this table, the above query...

+-----------------------+
|        skills         |
+-----------------------+
|        php            |   => matches
+-----------------------+
| php,laravel,html      |   => does not match--why?
+-----------------------+
|       html            |   => matches
+-----------------------+
|php,html,laravel,nodejs|   => does not match -- why?
+-----------------------+

Thanks in Advance!!!

You misunderstand how FIND_IN_SET works.

  • FIND_IN_SET('html', 'php,html,laravel,nodejs') is true, because the string 'html' is in the set 'php,html,laravel,nodejs' .
  • FIND_IN_SET('php,laravel,html', 'php,html,laravel,nodejs') is false, because the string 'php,laravel,html' is not in the set 'php,html,laravel,nodejs' .

Don't store values separated in a database table column. Have a separate table to link the single skills to each jobs_posted_by_employer record in order to query the data easily.

@Goutham, you can do what you want by using a loop in PHP to build a set of OR statements that takes each element of your string array and creates successive individual find_in_set statements with an OR between them. What you want to end up with is a query that checks for each element in your array, against the set. And don't implode your array into a string, because you need to use it as an array.

$skills = array('php','html','laravel','nodejs');

$sql = "SELECT * FROM jobs_posted_by_employer WHERE ";
for($x=0;$x<count($skills);$x++){
    if($x>0){$sql .=" OR ";}
    $sql .=" WHERE FIND_IN_SET(".$skills[$x].", :array)";
}
$sql .=";";

$stmt = $db->prepare($sql);

$stmt->bindParam('array', $skills);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM