Zend Framework 1.12 Db Select -嵌套where,在condition中使用多个问号值


Zend Framework 1.12 Db Select - nested WHEREs using multiple values for question marks in condition

我使用的是Zend Framework 1.12.3。我需要创建一个包含嵌套where的查询,例如

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"))确实有效,但是它不能像?那样防止注入攻击

看代码,我看没有办法做到这一点,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);

我将使用命名参数进行绑定,如下所示:

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