简体   繁体   中英

How to use zend_db_select to update when there is two clause

I want to update an entry in the table when 2 conditions are met.

I have this statement, but it is only for one where condition

$this->dbo->update('mytable', $data, $this->dbo->quoteInto('id= ?', $id));

Instead of just checking where for just "id", i want to check for userid also..

Appreciate any help.

Something similar to this should work as the $where argument will accept and parse an array, reference the _whereExpr() method in Zend_Db_Adapter_Abstract for the code on how the $where arg is processed:

$this->dbo->update('mytable', $data, array('id= ?'=> $id, 'user_id=?'=>$userId));

I'm going to suggest that you may wish to alter you approach and use the save() method of Zend_Db_Table_Row instead of update. Here's an example.

 public function saveUser($id, array $userData, $userId = null)
    {
        //$this->getDbAdapter is a placeholder for your choice of db adapters, I suggest a DbTable model that extends Zend_Db_Table_Abstract
        $select = $this->getDbAdapter()->select();
        //if userId is not null build a where clause
        if (!is_null($userId)) {          
            $select->where('user_id = ?', $userId);
        }
        //build where clause for primary key, two where() in select() will be 'AND' use orWhere() for 'OR'
        $select->where('id = ?', $id);
        //fetch the row you wish to alter
        $row = $this->getDbAdapter()->fetchRow($select);
        //assign the data to the row, you can update any or all columns
        $row->username = $userData[username];
        $row->user_id = $userData[user_id];
        //ect...

        //save the new data to the row, will only update changed coluns
        $row->save();
        //return the whole for use in other ways, save() typically only returnbs the primary key.
        return $row;
    }

Yes this method is a little more verbose and maybe a touch more complicated. However as you start bumping up against the limits of 'INSERT' and 'UPDATE', save() can provide some useful functionality.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM