2014-07-16 55 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'));