I'm using Zend Framework 1.12.3. I need to create a query that hasnested WHEREs, such as
SELECT * FROM table1
WHERE (id = 'foo' AND name = 'bar') OR (grade = 123)
Here's my attempt
$this->getDbTable()->select()
->from($this->getDbTable(), array('*')
->where('id = ? AND name = ?', $foo, $bar)
->orWhere('grade = ?', $grade);
However, the outcome is
SELECT * FROM table1
WHERE (id = 'foo' AND name = 'foo') OR (grade = 123)
instead of name = 'bar'
Basically, I cannot use multiple ?
s assigning each ?
a different value. Do you know any solution?
Thanks
LE: using a WHERE condition such as ->where("id = $foo and name = $bar")
does work, however it doesn't prevent injection attacks like the ?
does
Looking at the code, I see no way to do it, the where clause only works with a condition, but I think that adding parentheses, you can manage the AND and OR with the right priorities.
Try this:
this->getDbTable()->select()
->from($this->getDbTable(), array('*')
->where('(id = ?', $foo) // add '(' before condition
->where('name = ?)', $bar) // add ')' after condition
->orWhere('grade = ?', $grade);
I would use named params for binding, like so:
$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'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.