2014-01-21 25 views
0

Hy, 我有一些问题与Zend_Db_Select。 我有2个变量:类别和城市。这2个变量可能有一个值,或者它们可能未被设置。 所以,我确认:Zend_Db_Select:条款中的倍数

$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) 
     ; 

的问题是我怎么能如果城市为空,则从我的查询中删除('')。 谢谢!

回答

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注入。