您能帮我解决这个foreach循环吗?

时间:2018-07-10 17:12:08

标签: php mysql database search

$cat_id=$_GET['cat_id'];
$catEx = explode(' ',$cat_id);
foreach($catEx as $exCat)
{
    $looped .= 'ad_cat LIKE'.' '.'%'."$exCat".'%'.' OR '.'ad_title LIKE'.' '.'%'."$exCat".'%'.' OR '.'ad_sub_cat LIKE'.' '.'%'."$exCat".'%'.' OR '.'ad_description LIKE'.' '.'%'."$exCat".'%' ;
}

我需要这样做,以便搜索栏搜索多个单词。

3 个答案:

答案 0 :(得分:0)

如@aynber在评论中所述

使用sprintf

 sprintf ( 'column like "%%s%" or column like "%%s%"', 'string', 'string');

答案 1 :(得分:0)

在每组您喜欢的条件周围加上括号,以便在每一列中检查每个值。

$cat_id=$_GET['cat_id'];
$catEx = explode(' ',$cat_id);
foreach($catEx as $exCat) {
    $looped .= "(ad_cat         LIKE '%$exCat%' OR 
                 ad_title       LIKE '%$exCat%' OR 
                 ad_sub_cat     LIKE '%$exCat%' OR 
                 ad_description LIKE '%$exCat%') OR ";
}
$looped = trim($looped,' OR '); //just added some spaces

答案 2 :(得分:0)

您可以尝试使用此代码

$cat_id=$_GET['cat_id'];//cute cat
$catEx = explode(' ',$cat_id);
$looped = [];
foreach($catEx as $exCat) {
    $looped[] = "ad_cat         LIKE '%$exCat%' OR 
                 ad_title       LIKE '%$exCat%' OR 
                 ad_sub_cat     LIKE '%$exCat%' OR 
                 ad_description LIKE '%$exCat%'";
}
echo implode(" OR ",$looped);