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

Paginating Database Records (PHP)

class Users extends Model{

function Users(){

// call the Model constructor

parent::Model();

// load database class and connect to MySQL

$this->load->database();

}

function getAllUsers(){

$query=$this->db->get('users');

if($query->num_rows()>0){

// return result set as an associative array

return $query->result_array();

}

}

function getUsersWhere($field,$param){

$this->db->where($field,$param);

$query=$this->db->get('users');

// return result set as an associative array

return $query->result_array();

}

// get 5 rows at a time

function getUsers($row){

$query=$this->db->get('users',5,$row);

if($query->num_rows()>0){

// return result set as an associative array

return $query->result_array();

}

}

// get total number of users

function getNumUsers(){

return $this->db->count_all('users');

}

}


Reference