我正在努力使我的编码更有效率,如果没有选择任何内容,我仍然坚持如何告诉查询显示所有类别。
我有15个用户可以选择的类别,如果没有选择,则显示所有项目。而不是做AND .. AND .. AND 15次,如果没有选择,是否有一个更聪明的方法吗?
这适用于一个类别选择:
$cate = mysql_query("SELECT * FROM `posts` ORDER BY `id` ASC");
while($row = mysql_fetch_assoc($cate)){
if($user_data['category'] === $row['id']) {
echo '<li>'.$row['name'].'</li>';
}
}
$category_list = "AND `category_id` = '".$user_data['category']."'";
答案 0 :(得分:1)
您应该动态生成查询
// General query
$query = "SELECT * FROM `posts`";
// If category selected
if ($user_data['category'] != 0) {
$query .= " WHERE `category_id` = '".$user_data['category']."'";
}
// Order
$query .= " ORDER BY `id` ASC";
// Run query
$cate = mysql_query($query);
或者可以使用Ternary Operator
简化:
// Generate query
$query = "SELECT * FROM `posts` ".($user_data['category'] != 0 ? "WHERE `category_id` = '".$user_data['category']."'" : "" )." ORDER BY `id` ASC";
// Run query
$cate = mysql_query($query);