多个条件php / mysql

多个条件php / mysql

问题描述:

I'm working on a multi critera search on php/mysql, this search has 5 entries: - Type, Price Min - Price Max , Qty Min - Qty Max :

$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' " ;

This works just fine, but the user have to fill all the entries. And my idea is that the user can enter only Type, or Type and Price, or just Qty and so .. I tried to use the OR clause but I didn't make it work well.

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

notice that if a variable is an empty string, its condition is always satisfied.

Split your query up into parts. It's easier to use a query-assembly class for occasions such as this. And of-course PDO.

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


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

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

$results = $query->execute();