当SQL查询中的值为空时,如何忽略AND field = value?

时间:2011-07-31 00:56:57

标签: php mysql sql

我通过表单提交价格和category_id,然后查询显示结果。我的内容如下。

$s = mysql_real_escape_string($_GET["s"]);
$c = mysql_real_escape_string($_GET["c"]);

SELECT COUNT(id) FROM products WHERE price <= '$s' AND category_id = '$c'

如果用户未选择任何类别且其值为空,则不显示任何内容。如何解决如果$c没有任何值而忽略AND category_id = '$c'

的查询

我想为此目的创建第二个查询,但还有其他方法吗?

4 个答案:

答案 0 :(得分:4)

这样的事情应该有效:

$s = mysql_real_escape_string($_GET["s"]);
$c = (int) $_GET["c"];

$qpart = ($c > 0 ? " AND category_id = $c " : '');
$qry = "SELECT COUNT(id) FROM products WHERE price <= '$s' ". $qpart;

答案 1 :(得分:2)

像这样:

if(isset($c)){

$cat = " AND category_id = '$c'"

}

$sql = "SELECT COUNT(id) FROM products WHERE price <= '$s'" . $cat;

答案 2 :(得分:1)

$addition = '';
if(isset($c) && !empty($c) {
  $addition = ' AND category_id = ' . $c;
}

$qry = "SELECT COUNT(id) FROM products WHERE price <= '$s'" . $addition;

答案 3 :(得分:0)

如何使用简单的逻辑? 如果没有提供参数,它应该使列检查短路并选择所有行。

SELECT COUNT(id) 
FROM products 
WHERE ($s = 0    OR price <= $s) AND 
      ('$c' = '' OR category_id = '$c')