检查Database with PHP中是否存在逗号分隔值

时间:2015-09-22 06:15:39

标签: php mysql

我需要检查数据库中是否存在逗号分隔值。我的数据库也以逗号分隔。

我的字符串在数据库中保存为“1,2,3,4,5”。

我的搜索字符串是$ bloggerscat =“2,5”

我试过了

(B.category_id LIKE ('%,$bloggerscat') OR B.category_id LIKE ('%$bloggerscat,%') OR B.category_id = '".$bloggerscat."')

没有得到正确的结果。请帮帮我。

高级谢谢......

2 个答案:

答案 0 :(得分:4)

你可以这样做,

$bloggerscat = '2,5'; // Your input here (string)

$set = explode(',',$bloggerscat); // get the numbers in $set array

$query = 'SELECT * FROM `table` WHERE '; // construct query

foreach ($set as $search)
{
    $query .= "FIND_IN_SET($search, column_name) OR "; // append every time for set 
}

$query = rtrim($query, ' OR'); // remove last OR

echo $query; // test

将产生

SELECT * FROM `table` WHERE FIND_IN_SET(2, column_name) OR FIND_IN_SET(5, column_name)

将为您提供来自column_name列的结果,其中逗号分隔的集合的值为25

答案 1 :(得分:-1)

您必须将字符串存储为",1,2,3,4,5和#34;在数据库中 然后试试这段代码

$currStr        =   "2,5";
$explCurrStr    =   explode(",",$currStr);
foreach($explCurrStr as $key=>$all){
    if($key==0){
        $sql.=" B.category_id LIKE ('%,".$all.",')  ";
    }else{
        $sql.=" OR B.category_id LIKE ('%,".$all.",')  ";
    }
}