0

嗨,我有一些关于 Zend_Db_Select 的问题。我有 2 个变量:类别和城市。这 2 个变量可能有值,也可能未设置。所以我验证:

$status = '`p`.status = 1';
    if($catID){
        $catSQL =  "`p`.parent = {$catID}";
    }else{
        $catSQL = '1=1';
    }

    if($city){
        $citySQL =  "`pm`.`meta_key` = 'oras' and `pm`.`meta_value` = {$city}";
        $citySelect = array('pm' => 'postsmeta');
        $condCity = "`p`.`ID` = `pm`.`parent_id`";
    }else{
        $citySQL = '1=1';
        $citySelect = NULL;
        $condCity = '1=1';
    }

现在这是我的查询:

 $select = $db->select()
         ->from( array('p' => 'posts'))
         ->from($citySelect)
         ->where($status)
         ->where($catSQL)
         ->where($condCity)
         ->where($citySQL)
         ;

问题是,如果城市是空的,我有类似的东西

 $select = $db->select()
         ->from( array('p' => 'posts'))
         ->from('')
         ->where(1=1)
         ->where(1=1)
         ->where(1=1)
         ->where(1=1)
         ;

问题是如果 city 为空,我如何从查询中删除 from('') 。谢谢!

4

1 回答 1

2

简单地,

$select = $db->select()
->from( array('p' => 'posts'));
if($someConditionIsTrue) {
    $select->join($table, $condition);
}
$select->where('field_value = ?', 'value1');
if($someConditionIsTrue) {
    $select->where('another_field = ?', 'value 2');
}

希望能帮助到你。

请使用此语法$select->where('another_field = ?', 'value 2');正确转义值以防止 SQL 注入。

于 2014-01-21T14:49:09.033 回答