Search code examples
phpmysqlzend-frameworkzend-paginator

how to use zend paginate without loading all the results of a database


So the way I see zend paginate work is that you do:

$paginator = Zend_Paginator::factory($results);
$paginator->setItemCountPerPage($itemCount);
$paginator->setPageRange($pageRange);

Where $results is the result of loading a bunch of items from a database in the form of

"SELECT * FROM table WHERE etc"

Then zend paginate will count the number of results and generate the page ranges automatically...

But if you do this then you're going to have to fetch all results of a database which I see as a waste since only one page is displayed at a time and therefore you only need to fetch the items for that page...

how do you make zend paginate to be able to calculate the correct page ranges and numbers without resorting to fetching all the results of an entire table?


Solution

  • Using the factory method you can send an instance of Zend_Db_Select or Zend_Db_Table_Select. If you're class extends Zend_Db_Table_Abstract you can simply build a select query from it and then send this. If not you can create an instance and send it, see the example from the docs:

        $adapter = new Zend_Paginator_Adapter_DbSelect($db->select()->from('posts'));
        $adapter->setRowCount(
            $db->select()
               ->from(
                    'item_counts',
                    array(
                       Zend_Paginator_Adapter_DbSelect::ROW_COUNT_COLUMN => 'post_count'
                    )
                 )
        );
    
    $paginator = new Zend_Paginator($adapter)
    

    http://framework.zend.com/manual/en/zend.paginator.usage.html#zend.paginator.usage.dbselect