如何将这两个查询合并为一个,这样我就不必一次又一次地重复相同的行?
if(empty($cat_id))
{
$sql = "
SELECT *
FROM root_category_contacts
ORDER by cat_order ASC
";
$items_category = $connection->fetch_all($sql);
}
else
{
$sql = "
SELECT *
FROM root_category_contacts
WHERE root_category_contacts.cat_id != ?
ORDER by cat_order ASC
";
$items_category = $connection->fetch_all($sql,array($cat_id));
}
当我没有WHERE
时,我不需要cat_id
子句。
可行吗?
答案 0 :(得分:1)
测试是否?为null或等于cat_id。像这样:
根据xdazz的评论修改。假设cat_id> 0
$sql = "
SELECT *
FROM root_category_contacts
WHERE root_category_contacts.cat_id != ?
ORDER by cat_order ASC"
if(empty($cat_id)) {
$cat_id = 0;
}
$items_category = $connection->fetch_all($sql,array($cat_id));
答案 1 :(得分:-1)
if(empty($cat_id)) $where = "";
else $where = "WHERE root_category_contacts.cat_id != '$cat_id'"
$sql = "
SELECT *
FROM root_category_contacts
$where
ORDER by cat_order ASC
";
$items_category = $connection->fetch_all($sql);