Zend DB fetchAll(): where as array

18,433

Solution 1

From Zend_Db_Table_Abstract

/**
 * Fetches all rows.
 *
 * Honors the Zend_Db_Adapter fetch mode.
 *
 * @param string|array|Zend_Db_Table_Select $where  OPTIONAL An SQL WHERE clause or Zend_Db_Table_Select object.
 * @param string|array                      $order  OPTIONAL An SQL ORDER clause.
 * @param int                               $count  OPTIONAL An SQL LIMIT count.
 * @param int                               $offset OPTIONAL An SQL LIMIT offset.
 * @return Zend_Db_Table_Rowset_Abstract The row results per the Zend_Db_Adapter fetch mode.
 */
public function fetchAll($where = null, $order = null, $count = null, $offset = null)

So you are incorrect, fetchAll() does accept an array of where clauses.

Your array should look like this (based on the definition in Zend_Db_Select)

$where = array(
    'id > 0',
    'enabled = ?' => 1
);

Solution 2

First we will look at your original code:

$wheres = array('id > 0', 'enabled' => 1);

Remember that => is an assignment operator. In your array above you start out with string automatically assigned to key 0. The next element is the number 1 assigned to the key 'enabled'. The solution proposed in answer 1 assigns the number 1 to key 'enabled = ?'.

Try this:

$all = new ORM_Model_DbTable_Asset();
$where = array();
$where[] = 'id > 0';
$where[] = $all->quote_into('enabled >= ?', 1, 'INTEGER');  // 1 could be a variable
$result = $all->fetchAll($where);
Share:
18,433
azz0r
Author by

azz0r

Updated on November 21, 2022

Comments

  • azz0r
    azz0r over 1 year

    I'm confused as to why Zend_DB doesn't accept an array of WHERE clauses - or am I incorrect? I have made the following work around:

    $all = new ORM_Model_DbTable_Asset();
    $wheres = array('id > 0', 'enabled' => 1);
    $all = $all->fetchAll(implode(' AND ', $wheres))->toArray();
    

    for what I hoped would be:

    $all = new ORM_Model_DbTable_Asset();
    $wheres = array('id > 0', 'enabled' => 1);
    $all = $all->fetchAll($wheres)->toArray();
    

    Slightly disappointing, am I missing something?

    • Phil
      Phil about 12 years
      I'd avoid overwriting your $all DB Table object with the results array
  • RockyFord
    RockyFord about 12 years
    in order to use this notation wouldn't $where have to be a select() object? $where = $this->select(); $where->where(array('id > 0', 'enabled =?', 1)); or something similar?
  • Phil
    Phil about 12 years
    @RockyFord That's what happens internally when the $where (first) argument of fetchAll() is an array