2012-08-14 70 views
2

我想要一個先進的側邊欄,當有人使用搜索欄過濾結果。我有正常的搜索工作,並且還顯示了另一側欄上某個類別的項目數量(即價格範圍,品牌,條件),但現在我希望用戶點擊一個類別並縮小結果,例如您看到的內容newegg.com。PHP按類別過濾搜索結果數

這是我的搜索查詢:

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\">" 

和在我的功能使用案例:

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: 
    } 
    } 

但它沒有完成這項工作,而我在這一點上只是輸了。

有沒有更好的方法或不同的方法來實現這一目標?它不必使用大小寫或$ _GET。 謝謝你的時間。

回答

0

問題是您需要在您的OR語句中添加括號。我會這樣做:

$search_query .= ' WHERE 1'; 

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

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