2012-06-04 105 views
0

我工作在PHP/MySQL的多性判據的搜索,這個搜索有5項: - 類型,價格最小 - 最大價格,數量最小 - 最大數量:多個條件的PHP/MySQL

$Type = $_POST['Type']; 
$Pmin = $_POST['Pmin']; 
$Pmax = $_POST['Pmax']; 
$Qtmin = $_POST['Qtmin']; 
$Qtmax = $_POST['Qtmax']; 
$query = "SELECT * FROM products where type_product='$Type' 
and price_min<='$Pmin' 
and price_max>='$Pmax' 
and qty_min<='$Qtmin' 
and qty_max>='$Qtmax' " ; 

這工作得很好,但用戶必須填寫所有條目。我的想法是,用戶只能輸入類型,或類型和價格,或只是數量等。 我試圖使用OR子句,但我沒有讓它工作正常。

+2

SQL注入。如果你使用mysqli :: real_query(...)你很好,雖然 –

+0

你的問題很不清楚...... – Norse

回答

1
where 
    (a = '$a' or '$a' = '') 
and (b <= '$b' or '$b' = '') 
and (c >= '$c' or '$c' = '') 

通知,如果一個變量是一個空字符串,其條件總是被滿足。

+0

謝謝,正是我想要的。它現在的作品:) – Common

+0

不客氣。 – goat

5

將查詢拆分爲多個部分。在這種情況下使用查詢 - 彙編類更容易。和當然PDO。

$query->select('columns from MyTable') 
->where('deleted = 0'); 


if (condition) { 
    $query->where('field = ?', $value); 
} 

if (condition) { 
    $query->where('field != ?', $value); 
} 

$results = $query->execute();