我通过表单提交价格和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'
?
我想为此目的创建第二个查询,但还有其他方法吗?
答案 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')