3.5. Zend_Db_Table_Rowset
Prev | Chapter 3. Zend_Db | Next

## 3.5. Zend_Db_Table_Rowset

### 3.5.1. Introduction

Zend_Db_Table_Rowset is an iterator for Zend_Db_Table_Row object collections. In general, you do not instantiate Zend_Db_Table_Rowset by itself; instead, you retrieve a Zend_Db_Table_Rowset as the return result from a call to Zend_Db_Table::find() or fetchAll(). You can then iterate through the collected Zend_Db_Table_Row objects and modify them as you wish.

### 3.5.2. Fetching a Rowset

The first thing to do is instantiate a Zend_Db_Table class.

    <?php
    // set up an adapter
    require_once 'Zend/Db.php';
    $params = array (
        'host'     => '127.0.0.1',
        'username' => 'malory',
        'password' => '******',
        'dbname'   => 'camelot'
    );

    $db = Zend_Db::factory('PDO_MYSQL', $params);

    // set the default adapter for all Zend_Db_Table objects
    require_once 'Zend/Db/Table.php';
    Zend_Db_Table::setDefaultAdapter($db);

    // connect to a table in the database
    class RoundTable extends Zend_Db_Table {}
    $table = new RoundTable();
    ?>

Next, retrieve many records from the database using Zend_Db_Table::find() with multiple keys, or by using Zend_Db_Table::fetchAll(); the returned result will be a Zend_Db_Table_Rowset object that will let you iterate through the individual Zend_Db_Table_Row objects in the record set.

    <?php
    // fetch many records from the table
    $rowset = $table->fetchAll();

    //
    // $rowset is now a Zend_Db_Table_Rowset object composed of
    // one Zend_Db_Table_Row object per record in the results
    //
    ?>

### 3.5.3. Iterating Through the Rowset

Zend_Db_Table_Rowset implements the SPL Iterator interface, which means you can loop through Zend_Db_Table_Rowset objects like arrays using foreach(). Each value you retrieve this way will be a Zend_Db_Table_Row that corresponds to one record from the table; you can then view, modify, and save the properties for that record.

    <?php
    // connect to a table in the database
    class RoundTable extends Zend_Db_Table {}
    $table = new RoundTable();

    // fetch many records from the table
    $rowset = $table->fetchAll();

    // display them all
    foreach ($rowset as $row) {
        // $row is a Zend_Db_Table_Row object
        echo "<p>" . htmlspecialchars($row->nobleTitle) . " "
           . htmlspecialchars($row->firstName) . "'s "
           . "favorite color is " . htmlspecialchars($row->favoriteColor)
           . ".</p>\n";

        // update the number of times we have displayed this row,
        // (which maps to a column in the table "times_displayed")
        $row->timesDisplayed ++;

        // save the record with the new information
        $row->save();
    }
    ?>

Prev | Up | Next
3.4. Zend_Db_Table_Row | Home | Chapter 4. Zend_Feed