PHP按类别过滤搜索结果

时间:2012-08-14 15:38:15

标签: php mysql filter search-engine filtering

我正在尝试使用高级侧边栏,在有人使用搜索栏时过滤结果。我有常规搜索工作,并使其显示另一个侧栏上的类别中的项目数(即价格范围,品牌,条件)但现在我希望用户点击一个类别并缩小结果,就像你看到的那样newegg.com。

这是我的搜索查询:

 function build_query($product_search) {
$search_query = "SELECT * FROM tbl_product p INNER JOIN tbl_brand b ON p.br_id = b.br_id";
$clean_search = str_replace(',', ' ', $product_search);
$search_word = explode(' ', $clean_search);
$final_search_words = array();
if (count($search_word) > 0) {
    foreach ($search_word as $word) {
        if (!empty($word)) {
            $final_search_words[] = $word;
        }
    }
}
$where_list = array();
if (count($final_search_words) > 0) {
    foreach($final_search_words as $word) {
        $where_list[] = "p.pd_name LIKE '%$word%'";
    }
}
$where_clause = implode(' OR ', $where_list);
if(!empty($where_clause)) {
    $search_query .= " WHERE $where_clause";
}

我的侧边栏计算类别的内容相同:

function narrow_query($product_search) {
$search_query = "SELECT p.pd_name, p.pd_con, b.br_name AS name, c.cat_name AS cat,
    COUNT(p.pd_con) AS con, COUNT(b.br_name) AS brand, COUNT(c.cat_name) AS cat_c,
    COUNT(CASE WHEN p.pd_price >= '00.01' AND p.pd_price <= '99.99' THEN 1 END) AS cnt1,
    COUNT(CASE WHEN p.pd_price >= '100.00' AND p.pd_price <= '199.99' THEN 1 END) AS cnt2,
    COUNT(CASE WHEN p.pd_price >= '200.00' AND p.pd_price <= '299.99' THEN 1 END) AS cnt3,
    And so on and so on...
                FROM tbl_product p JOIN tbl_brand b ON b.br_id = p.br_id
                JOIN tbl_category c ON c.cat_id = p.cat_id";
$clean_search = str_repl...
    (Same word filter code as above)

现在我通过抓住$ _GET获得了一些有用的东西:

"<a href=\"" . $_SERVER['PHP_SELF'] . "?productsearch=" . $product_search . "&narrow=" . $row['cat'] . "$link=1\">"

并在我的函数中使用case:

function any_query($product_search, $link, $narrow) {
previous info from above...
  if(!empty($link)) {
    switch($link)
    case 1:
      $search_query .= " AND b.br_name = '$narrow'";
      break;
    default:
    }
    }

但它没有完成这项工作,我现在只是迷失了。

有没有更好的方法或不同的方法来实现这一目标?它不必使用case或$ _GET。 谢谢你的时间。

1 个答案:

答案 0 :(得分:0)

问题是您需要在OR语句周围添加括号。我会这样做:

$search_query .= ' WHERE 1';

if (!empty($where_clause)) {
    $search_query .= " AND ($where_clause)";
}

if (!empty($narrow)) {
    $search_query .= " AND $narrow";
}