Search code examples
zend-frameworkzend-dbzend-db-table

OR clause in Zend DB update?


I'd like to do a Zend db update with an OR clause. What would be the equivalent statement to:

UPDATE mail
SET message_read = 1
WHERE id = 5
OR id = 10

Solution

  • When calling Zend_Db_Adapter::update(), multiple WHERE conditions will automatically be combined using AND (line 698 of Zend/Db/Adapter/Abstract.php in function _whereExpr).

    You can get around this by creating your own Zend_Db_Expr which you will use as the WHERE condition and it will be left untouched.

    For example:

    $where[] = new Zend_Db_Expr(
            $table->getAdapter()->quoteInto('id = ?', 5) . ' OR ' .
            $table->getAdapter()->quoteInto('id = ?', 10)
    );
    
    // resulting expression:
    //   WHERE (id = 5 OR id = 10)
    
    $table->update($data, $where);
    

    If you had additional WHERE conditions, they would be combined with the OR condition by an AND.

    Example:

    $where[] = new Zend_Db_Expr(
            $table->getAdapter()->quoteInto('id = ?', 5) . ' OR ' .
            $table->getAdapter()->quoteInto('id = ?', 10)
    );
    $where[] = $table->getAdapter()->quoteInto('type = ?', 'sometype');
    
    // resulting expression:
    //   WHERE (id = 5 OR id = 10) AND (type = 'sometype')