foreach and count can operate on the object. * *

To iterate over the results, use either one of the following to constructs * *

 * // Using result as an iterator.
 * foreach ($row as $res) {
 *     // $row is an associative array.
 * }
 *  
 * // Or as an old-fashioned while loop.
 * while ($row = $res->next()) {
 *    // $row is an associative array here too.
 * }
 * 
* * @author Samuel Sjöberg, http://samuelsjoberg.com */ class DBResult implements Iterator, Countable { /** * The result set. * @access private */ private $result; /** * Array representation of the result set. Used as cache. * @access private */ private $rows = array(); /** Position in the result set. */ private $pos = -1; /** * Create a new result. * * @param mixed $result the mysql result set */ public function __construct($result) { $this->result = $result; } /** * Get the first row in the result set. * @return the first row in the result set, or null * if result contains no rows. */ public function first() { $this->rewind(); return $this->current(); } /** * Get the next row in the result set as an associative array. This method * is part of the Iterator interface, but can also be used * directly in a while loop. * * @return Next row in the result set as an associative array. */ public function next() { $this->pos += 1; if (!isset($this->rows[$this->pos])) { $this->rows[$this->pos] = mysql_fetch_assoc($this->result); } return $this->current(); } /** {@inheritDoc} */ public function valid() { return $this->pos < 0 || is_array($this->current()); } /** {@inheritDoc} */ public function current() { return $this->rows[$this->pos]; } /** {@inheritDoc} */ public function rewind() { $this->pos = -1; $this->next(); } /** {@inheritDoc} */ public function key() { return $this->pos; } /** * Get the number of rows in the result set. * * @return Number of rows in the result set. */ public function count() { return mysql_num_rows($this->result); } /** * Return the full result set in an array. If only one row exists, that row * is returned, otherwise an array of rows will be returned. * * @return if only one row exists, that row is returned, otherwise all rows * are returned as an array. */ public function toArray() { if (count($this->rows) != count($this)) { while ($row = $this->next()); } return count($this->rows) == 1 ? $this->rows[0] : $this->rows; } } ?>