dragon0118 2012-05-06 16:13
浏览 15
已采纳

为什么我的php / mysql搜索字符串只与LAST关键字匹配?

I have a search function that is supposed to take all the keywords in an array from $keywords_search and then create the correct mySQL statement to get the results. The problem is, when I search for multiple keywords, it seems to find only results that match the LAST keyword in the array. What am I doing wrong?

Here is the code:

$sr='';
foreach(explode(" ",$keywords_search) as $value){

    $sr="a.name LIKE '%".$value."%' AND";

}
$query[] = substr($sr,0,-4);

It's supposed to search for

a.name LIKE '%keyword1%' AND
a.name LIKE '%keyword2%' AND
a.name LIKE '%keyword3%'

The var_dump(); for $query shows only the output for the last keyword, while the var_dump(); for the $keywords_search shows all keywords.

  • 写回答

1条回答 默认 最新

  • douxin9135 2012-05-06 16:15
    关注

    make it like this

    $sr='';
    foreach(explode(" ",$keywords_search) as $value){
    
        $sr .= " a.name LIKE '%".$value."%' AND";
    
    }
    $query[] = substr($sr,0,-4);
    

    you forgot to put a . for appending.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?