Thursday, September 18, 2008

Method #1

The first method is using Pager to create the links only, and let you fetch the relevant records on your own. Instead of passing the array of data to paginate to Pager, you just pass the number of records. In the following example, we'll fetch the records from a table containing some products. The PEAR::MDB2 DBAL is used here, but how you fetch the records isn't relevant.


require_once 'Pager/Pager.php';
require_once 'MDB2.php';

//skipped the db connection code...
//let's just suppose we have a valid db connection in $db.

//first, we use Pager to create the links
$num_products = $db->queryOne('SELECT COUNT(*) FROM products');
$pager_options = array(
'mode' => 'Sliding',
'perPage' => 10,
'delta' => 2,
'totalItems' => $num_products,
);

$pager = Pager::factory($pager_options);

//then we fetch the relevant records for the current page
list($from, $to) = $pager->getOffsetByPageId();
//set the OFFSET and LIMIT clauses for the following query
$db->setLimit($pager_options['perPage'], $from - 1);
$query = 'SELECT prod_name, prod_description FROM products';
$products = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);

//show the results
echo '
    ';
    foreach ($products as $product) {
    echo '
  • '.$product['prod_name'].': '.$product['prod_description'].'
  • ';
    }
    echo '
';

//show the links
echo $pager->links;
?>

Reference

No comments: