简体   繁体   English

多种条件php / mysql

[英]Multiple conditions 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 : 我正在php / mysql上进行多critera搜索,此搜索有5个条目:-类型,价格最小值-价格最大值,数量最小值-数量最大值:

$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. 我的想法是用户只能输入Type(类型),Type(类型)和Price(价格),或者Qty(数量)等等。.我尝试使用OR子句,但效果不理想。

Split your query up into parts. 将您的查询分为几部分。 It's easier to use a query-assembly class for occasions such as this. 在诸如此类的情况下使用查询组装类会更容易。 And of-course PDO. 当然还有PDO。

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


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

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

$results = $query->execute();
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. 请注意,如果变量是空字符串,则其条件始终会得到满足。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM