MySQL:结合两个重复查询以使WHERE子句动态化

时间:2011-08-23 23:35:35

标签: php mysql sql pdo where-clause

如何将这两个查询合并为一个,这样我就不必一次又一次地重复相同的行?

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子句。

可行吗?

2 个答案:

答案 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);