我正在寻找一种更快,更清晰的方式来编写这些'如果' PHP中的语句。
if($type == "deals") {
if($city == "blank" && $category == "blank") {
$arr = $mysqli->query("SELECT id, hide FROM deals");
}
if($city !== "blank" && $category == "blank") {
$arr = $mysqli->query("SELECT id, hide FROM deals WHERE city=".$city."");
}
if($city == "blank" && $category !== "blank") {
$arr = $mysqli->query("SELECT id, hide FROM deals WHERE category=".$category."");
}
if(!$city == "blank" && $category !== "blank") {
$arr = $mysqli->query("SELECT id, hide FROM deals WHERE city=".$city." AND category=".$category."");
}
} else { ... same thing with different querys ... }
欢迎更好的替代方案的建议!
由于
答案 0 :(得分:3)
我多年没碰到php了。但是在伪代码中:
$whereParam = array();
$sql = array();
$sql[] = "SELECT id, hide FROM deals";
if($city !== "blank") $whereParam[] = "city=".$city;
if($category !== "blank") $whereParam [] = "category=".$category;
$where = implode(' AND ', $whereParm);
if($where !== '') $sql[] = $where;
$arr = $mysqli->query(implode(' WHERE ', $sql));
改进依赖于您的其他代码。
编辑:我想看看ORMS
答案 1 :(得分:1)
有一种实现相同功能的简洁方法,可以防止SQL注入,并且需要更少的代码!
$stmt = $mysqli->prepare("SELECT id, hide FROM deals WHERE id>? AND (city=? OR 1=?) AND (category=? OR 1=?)");
$cityIsBlank = ($city == "blank");
$categoryIsBlank = ($city == "blank");
$stmt->bindParam("isisi", $last_id, $city, $cityIsBlank, $category, $categoryIsBlank));
$stmt->execute();
如果任一参数为"空白",则1=1
的计算结果为true,数据库优化器基本上不会在查找中包含where子句。
您可以阅读有关如何使用预准备语句以及检索值here的更多信息。
答案 2 :(得分:0)
尝试动态构建查询。
$sql = "SELECT id, hide FROM deals";
$wheres = array("city" => $city, "category" => $category);
if (count($wheres) > 0) {
$sql .= " WHERE " . implode(" AND ", $wheres);
}
$arr = $mysqli->query($sql);
确保正确转义变量以避免SQL注入。你可以用这个:
$city = $mysqli->real_escape_string($city);
为每个变量。