2014-07-16 72 views
3

中使用多個值作爲問號的嵌套WHERE我使用的是Zend框架1.12.3。我需要創建那種有嵌套哪來的查詢,如Zend Framework 1.12 Db選擇 - 在條件

SELECT * FROM table1 
WHERE (id = 'foo' AND name = 'bar') OR (grade = 123) 

這是我嘗試

$this->getDbTable()->select() 
->from($this->getDbTable(), array('*') 
->where('id = ? AND name = ?', $foo, $bar) 
->orWhere('grade = ?', $grade); 

然而,結果是

SELECT * FROM table1 
WHERE (id = 'foo' AND name = 'foo') OR (grade = 123) 

,而不是name = 'bar'

基本上,我無法使用多個?分配每個?有不同的值。你知道任何解決方案嗎?

感謝

LE:使用WHERE條件如->where("id = $foo and name = $bar")沒有工作,但它並不妨礙注入攻擊的?確實

回答

1

看代碼,我看沒有辦法做到這一點, where子句只適用於某個條件,但我認爲添加括號後,可以用正確的優先級管理AND和OR。

試試這個:

this->getDbTable()->select() 
    ->from($this->getDbTable(), array('*') 
    ->where('(id = ?', $foo) // add '(' before condition 
    ->where('name = ?)', $bar) // add ')' after condition 
    ->orWhere('grade = ?', $grade); 
+0

這只是一個例子,我有多個嵌套何在。我會盡力而爲。 – Daniel

1

我會使用一個名爲PARAMS的結合,就像這樣:

$sql = $this->getDbTable()->select() 
     ->from($this->_name, array('*')) 
     ->where('id = :foo AND name = :bar') 
     ->orWhere('grade = ?', 'grade'); 
    $this->getDbTable()->fetchAll($sql, array('foo' => 'foo', 'bar' => 'bar')); 
相關問題