PHP pagination class - php

I am looking for a php pagination class, I have used a rather simple one in the past and it is no longer supported.
I was wondering if anyone had any recommendations ?
It seems pointless to build my own when there are probably so many good ones out there.

After more searching I decided that before I use a frameworked version I should fully understand what is involved in a paginator. So I built one myself. Thanks for the suggestions though!

I would suggest Zend_Paginator for the following reasons
It's loosely coupled and doesn't require the entire library.
The ZF community is larger than the PEAR community and is actively running security audits on code, and releasing maintenance versions.
It separates data sources by using the Adapter Pattern, and there are numerous examples of front end UI pattern implementations in the documentation.

Have you tried PEAR::Pager? Usage examples here.

you can try this:
Zebra_Pagination, a generic, Twitter Bootstrap compatible, pagination class written in PHP
check the link below:
http://stefangabos.ro/php-libraries/zebra-pagination

// pagination class
class Pagination
{
// database handle
private $dbh;
// total records in table
private $total_records;
// limit of items per page
private $limit;
// total number of pages needed
private $total_pages;
// first and back links
private $firstBack;
// next and last links
private $nextLast;
// where are we among all pages?
private $where;
public function __construct($dbh) {
$this->dbh = $dbh;
}
// determines the total number of records in table
public function totalRecords($query, array $params)
{
$stmt = $this->dbh->prepare($query);
$stmt->execute($params);
$this->total_records = $stmt->fetchAll(PDO::FETCH_COLUMN)[0];
if (!$this->total_records) {
echo 'No records found!';
return;
}
}
// sets limit and number of pages
public function setLimit($limit)
{
$this->limit = $limit;
// determines how many pages there will be
if (!empty($this->total_records)) {
$this->total_pages = ceil($this->total_records / $this->limit);
}
}
// determine what the current page is also, it returns the current page
public function page()
{
$pageno = (int)(isset($_GET['pageno'])) ? $_GET['pageno'] : $pageno = 1;
// out of range check
if ($pageno > $this->total_pages) {
$pageno = $this->total_pages;
} elseif ($pageno < 1) {
$pageno = 1;
}
// links
if ($pageno > 1) {
// backtrack
$prevpage = $pageno -1;
// 'first' and 'back' links
$this->firstBack = "<div class='first-back'><a href='$_SERVER[PHP_SELF]?pageno=1'>First</a> <a href='$_SERVER[PHP_SELF]?pageno=$prevpage'>Back</a></div>";
}
$this->where = "<div class='page-count'>(Page $pageno of $this->total_pages)</div>";
if ($pageno < $this->total_pages) {
// forward
$nextpage = $pageno + 1;
// 'next' and 'last' links
$this->nextLast = "<div class='next-last'><a href='$_SERVER[PHP_SELF]?pageno=$nextpage'>Next</a> <a href='$_SERVER[PHP_SELF]?pageno=$this->total_pages'>Last</a></div>";
}
return $pageno;
}
// get first and back links
public function firstBack()
{
return $this->firstBack;
}
// get next and last links
public function nextLast()
{
return $this->nextLast;
}
// get where we are among pages
public function where()
{
return $this->where;
}
}
Use:
$pagination = new Pagination($dbh);
$pagination->totalRecords('SELECT COUNT(*) FROM `photos` WHERE `user` = :user', array(':user' => $_SESSION['id']));
$pagination->setLimit(12);
$pagination->page();
echo $pagination->firstBack();
echo $pagination->where();
echo $pagination->nextLast();
Result:
<div class='first-back'><a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=1'>First</a> <a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=3'>Back</a></div>
<div class='page-count'>(Page 4 of 6)</div>
<div class='next-last'><a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=5'>Next</a> <a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=6'>Last</a></div>

public function make_pagination()
{
$total = 0;
$query = "SELECT COUNT(downloads.dn_id) FROM downloads WHERE downloads.dn_type = 'audios'";
$stmt = $this->conn->prepare($query);
$stmt->execute();
$total = $stmt->fetchColumn();
//echo 'row_count = ' . $total;
// How many items to list per page
$limit = 11;
// How many pages will there be
$pages = ceil($total / $limit);
// What page are we currently on?
$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default' => 1,
'min_range' => 1,
),
)));
// Calculate the offset for the query
$offset = ($page - 1) * $limit;
// Some information to display to the user
$start = $offset + 1;
$end = min(($offset + $limit), $total);
// The "back" link
$prevlink = ($page > 1) ? '« ‹' : '<span class="disabled">«</span> <span class="disabled">‹</span>';
// The "forward" link
$nextlink = ($page < $pages) ? '› »' : '<span class="disabled">›</span> <span class="disabled">»</span>';
// Display the paging information
echo '<div id="paging"><p>'.$prevlink.' Page '.$page.' of '.$pages. ' pages'. $nextlink.' </p></div>';
//prepare the page query
$query2 = "
SELECT * FROM downloads, map_artists, song_artists
WHERE map_artists.dn_id = downloads.dn_id
AND song_artists.artist_id = map_artists.artist_id
AND downloads.dn_type = 'audios' GROUP BY downloads.dn_id
ORDER BY downloads.dn_time DESC LIMIT :limit OFFSET :offset ";
$stmt2 = $this->conn->prepare($query2);
$stmt2->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt2->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt2->execute();
// Do we have any results?
if ($stmt2->rowCount() > 0) {
// Define how we want to fetch the results
$stmt2->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt2);
// Display the results
foreach ($iterator as $row) {
echo '<p>'. $row['dn_title'].' - '. $row['artist_name'].'</p>';
}
} else {
echo '<p>No results could be displayed.</p>';
}
}

Its Very possible that your SQL SELECT statement query may 1000 result into thousand of records. But its is not good idea to display all the results on one page. So we can divide this result into many pages as per requirement as pagination Class .
PAGINATE DATA WITH PAGINATION CLASS VERY EASY
pagination Class helps to generate paging
How To Use Pagination Class
visit this link for more info
http://utlearn.com/2017/02/15/pagination-class-use-pagination-class/
<?php
/**
* #package pagination class
* #version 1.0
*/
/*
#class Name: pagination
#Author: Ahmed Mohamed
#Version: 1.0
#Author URI: https://www.fb.com/100002349977660
#Website URI: http://www.utlearn.com
#class page URI: http://utlearn.com/2017/02/15/pagination-class-use-pagination-class
*/
include_once 'libs/config.php';
include_once 'libs/Database.php';
include_once 'libs/Model.php';
include_once 'libs/pagination.php';
if(!empty($_GET["page"]) and is_numeric($_GET["page"])){
$page = htmlspecialchars(strip_tags($_GET["page"]));
} else {
$page = 1;
}
// news = table name / you page URL / current page / true or false for full query
// its false i just use table name
$pag = new pagination("news", URL."?page=", 3, $page, false);
$pagination = $pag->pagination();
$data = $pag->data();
?>
<news>
<?php foreach($data as $news){ ?>
<header><h1><?=$news->title ?></h1> | <span><?=$news->date ?></span></header>
<div>
<?=$news->content ?>
</div>
<?php } ?>
</news>
<?=$pagination ?>

Related

set pagination pagenumber as default url

So i managed to build a working pagination system in php. But i want users to default to the first pagenumber of said pagination, so for example if somebody clicks on category 1 the URL will change to this website.php?category=1 i would like this to be website.php?category=1&pagenumber=1 as the default URL.
The reason why i want this is so i don't have to write 2 different query's: 1 if the category isset but no pagenumber, and 1 if both are set.
function getNews()
{
// check if category is get via URL
if (isset($_GET["category"]) && is_numeric($_GET["category"]) && intval($_GET["category"])) {
// bind get category to categoryId
$categoryId = intval($_GET["category"]);
// if category is 1
if ($categoryId == 1) {
try {
$db = new Connection();
$database = $db->openConnection();
if (isset($_GET["pagenumber"]) && is_numeric($_GET["pagenumber"]) && intval($_GET["pagenumber"])) {
$pageNumber = intval($_GET["pagenumber"]);
$itemsPerPage = 9;
$offset = ($pageNumber - 1) * $itemsPerPage;
$stm = $database->query("SELECT * FROM blog where blog.Categoryid = $categoryId LIMIT 9 OFFSET $offset ");
$stm->execute();
$rowNews = $stm->fetchAll(PDO::FETCH_ASSOC);
$totalItems = $database->query("SELECT COUNT(*) FROM blog where blog.Categoryid = $categoryId")->fetchColumn();
$totalPages = intval(ceil($totalItems / $itemsPerPage));
$previousButton = ($pageNumber + 1) - $totalPages;
$nextButton = ($pageNumber) * $totalPages;
$pageIndex = 0;
this is what i currently have(i cut out the pagination system, can paste it in if needed).
//
this is how i generate my category select
<?php
if (isset($_GET["category"])){
$db = new Connection();
$categoryId = $_GET["category"];
$database = $db->openConnection();
$stm = $database->query("SELECT * FROM category");
$stm->execute();
$fetchCategory = $stm->fetchAll(PDO::FETCH_ASSOC);
foreach ($fetchCategory as $cats) {
?>
<a class="dropdown-item" href="blog.php?category=<?php echo $cats["categoryid"]; ?>"><?php echo $cats["categorytitle"]; ?></a>
<?php
}
?>
<?php
}else{
$categoryId = 1;
}
?>
</div>
</div>
<?php
$categoryId = -1;
if (isset($_GET["category"]) && intval($_GET["category"])) {
$categoryId = intval($_GET["category"]);
switch ($categoryId) {
case 1:
// do query for category id 1
getNews();
break;
case 2:
// do query for category id 2
getEwarehouse();
break;
case 3:
// do query for category id 3
getPartners();
break;
default:
ifnotNumeric();
break;
}
} else {
ifnotSet();
}
?>
Some more general information:
Running laragon 4.0.15 with PHP 7.3.9
Using HeidiSQL 10.2.0.5599
Using PHPStorm 2019.2.2
if you need anymore code examples i can paste them in.

PHP videos multiple pages doesn't work correctly

I'm working on a simple vlog site project and I'm trying to show only 20 video thumbnail per page and I've wrote this code in the index to divide the videos to multiple pages and then pagination them ... the problem is that it shows the same first video's thumbnail 20 times per page for infinity pages.
I really need help with this code
<?php
require_once ('db.php') ;
require_once ('VideosApi.php') ;
$count = mysql_query('SELECT COUNT(id) AS numb FROM videos ORDER BY id');
$array = mysql_fetch_assoc($count);
$number = $array['numb'];
mysql_free_result($count);
$PerPage = 20;
$nbPage = ceil(abs($number/$PerPage));
if(isset($_GET['page']) && $_GET['page'] > 0 && $_GET['page'] <= $nbPage && preg_match('#^[0-9]+$#',$_GET['page'])){ $cPage = $_GET['page']; }
else{ $cPage = 1; }
$Query = mysql_query('SELECT * FROM Videos ORDER BY id LIMIT '.(($cPage-1) * $PerPage).','.$PerPage);
$videos = Videos_Get() ;
if ($videos == Null)
die ('problem');
$vcount = #count ($videos) ;
if ($vcount == 0)
die('no videos') ;
For ($i = 0; $i < $vcount; $i++)
{
$video = $videos [$i];
if ($video->time > 3600)
$duration = gmdate("H:i:s",$video->time);
else
$duration = gmdate("i:s",$video->time);
while($Rows = mysql_fetch_assoc($Query)){
echo ( "<div class=\"video\">
<img src=\"$video->img\"><span class=\"class-video-name\">$video->name</span>
<div class=\"class-video-footer\">
<span class=\"class-video-duration\">$duration</span>
</div>
</div>") ; }
} ?>
A few tips before we get to the answer proper:
Don't use mysql_*. That family of functions is now deprecated and support will be dropped in future versions of PHP. For code longevity, consider using MySQLi or PDO.
Use is_numeric() to check if a string has a numeric value. Using preg_match() is very load heavy for such a simple task.
Try to avoid using SELECT * inside of MySQL queries. Very rarely do you need everything from the table so fetching all fields for rows is very inefficient (especially if you're not using indexes optimally).
That having been said, I've taken some time to rewrite your code following the practices I've preached above. Below is the modified code, and underneath that an explanation of what was wrong:
Update db.php as follows:
<?php
$db = new PDO( 'mysql:dbname=DATABASE_NAME;host=127.0.0.1', 'DATABASE_USER', 'DATABASE_PASSWORD' );
?>
Now for your main file:
<?php
require_once 'db.php';
require_once 'VideosApi.php';
$count = $db->query( 'SELECT COUNT(id) AS total FROM videos' )->fetchObject();
$number = $count->total;
$perPage = 20;
$pages = ceil( $number / $perPage );
$page = ( isset($_GET['page']) ) ? $_GET['page'] : 1;
$page = ( $page < 1 || $page > $pages || !is_numeric($page) ) ? 1 : $page;
$offset = ($page - 1) * $perPage;
$query = $db->query( 'SELECT id, img, name, time FROM videos ORDER BY id LIMIT '.$offset.','.$perPage );
if( $query->rowCount() < 1 )
{
die( 'No videos' );
}
$html = '';
while( $video = $query->fetchObject() )
{
$duration = ($video->time > 3600) ? gmdate('H:i:s', $video->time) : gmdate('i:s', $video->time);
$html.= '<div class="video">';
$html.= "\n\t".'<a href=\"video.php?id='.$video->id.'">';
$html.= "\n\t\t".'<img src="'.$video->img.'" />';
$html.= "\n\t".'</a>';
$html.= "\n\t".'<span class="class-video-name">'.$video->name.'</span>';
$html.= "\n\t".'<div class="class-video-footer">';
$html.= "\n\t\t".'<span class="class-video-duration">'.$duration.'</span>';
$html.= "\n\t".'</div>';
$html.= "\n".'</div>';
}
echo $html;
?>
The problem with your original code is a little hard to determine since you do not provide the contents of VideosApi.php, which is where I assume you define Videos_Get(). Anyway, what I suspect is happening, is that Videos_Get() is actually ignoring all of your pagination, but as I say, it's difficult to diagnose because we can't see all of your code!

php image gallery pagination

I am trying to add a simple pagination to an image gallery but I reach a point where I don't get any error messages and it still is not working. I don't know where to look for a mistake.
My code is;
<?php
include 'core/init.php';
ini_set('display_errors', 'On'); // aan of uit
error_reporting(E_ALL);
?>
<body>
<div id="wrap">
<div id="header">
<h1>Rob Cnossen</h1>
</div>
<div id="titel">
<?php
if (isset($_GET['album_id'])) {
$album_id = $_GET['album_id'];
$album_data = $albums->album_data($album_id, 'name', 'description');
echo '<h2>', $album_data['name'], '</h2>';
$albums = $albums->get_albums();
$images = $images->get_images($album_id);
}
?>
</div>
<div id="sidebarleft">
<?php
if (empty($images)) {
echo 'Er zijn geen foto\'s in dit album';
} else {
foreach ($albums as $album) {
foreach ($images as $image) {
?><div id="fotoos"><?php
if ($image["album"] === $album["id"])
echo'<img src="uploads/thumbs/', $image["album"], '/', $image["img_name"],'" title="" /><div id="kruisje">_|</div>';
?></div><?php
}
}
}
?>
<div id="pagination">
<?php
$count_query = $db->prepare('SELECT * FROM images where album_id= ?');
$count_query->bindValue(1, $album_id);
try{
$count_query->execute();
}catch (PDOException $e){
die($e->getMessage());
}
$count = $count_query->fetchColumn();
if(isset($_GET['page'])){
$page = preg_replace("#[^0-9]#,",$_GET['page']);
}else{
$page = 1;
}
$limit = 2;
$lastPage = ceil($count/$limit);
if($page<1){
$page = 1;
}elseif($page>$lastPage){
$page = $lastPage;
}
$offset = ($page-1)*$limit;
$query = $db->prepare('SELECT image_id FROM images WHERE album_id= ? ORDER BY image_id DESC
LIMIT ?,?');
$query->bindValue(1, $album_id);
$query->bindParam(2, $offset, PDO::PARAM_INT);
$query->bindParam(3, $limit, PDO::PARAM_INT);
try{
$query->execute();
}catch (PDOException $e){
die($e->getMessage());
}
if($lastPage !=1){
if($page != $lastPage){
$next = $page + 1;
$pagination='Volgende';
}
if($page != $lastPage){
$prev = $page - 1;
$pagination.='Vorige';
}
}
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo $row['image_id'];//This echoes out two image id's, at the moment that is number 75 and 73
}
echo $pagination;
?>
</div>
</div>
</div>
</body>
The get_image function is;
public function get_images($album_id) {
$images = array();
$count_query = $this->db->prepare("SELECT `image_id`, `image_name`, `album_id`, `timestamp`, `ext` FROM `images` WHERE `album_id`=? ORDER BY `timestamp` DESC");
$count_query->bindValue(1, $album_id);
try{
$count_query->execute();
while ($images_row = $count_query->fetch(PDO::FETCH_ASSOC)) {
$images[] = array(
'id' => $images_row['image_id'],
'img_name' => $images_row['image_name'],
'album' => $images_row['album_id'],
'timestamp' => $images_row['timestamp'],
'ext' => $images_row['ext']
);
}
return $images;
}catch(PDOException $e){
die($e->getMessage());
}
}
I think there is something wrong in the $pagination variable but I don't know what.I got seven images in this album and the $limit is standing on 2, still all seven images is showing up. And if I click on a pagination link the url shows my that I clicked on a pagination link but that's all. If I click for example vife times on a next or previous link the url can show my this;http://www.robcnossen.nl/view_album.php?album_id=8?page=2?page=2?page=0?page=2?page=0
The site is http://www.robcnossen.nl/view_album.php?album_id=8
I hope you can see what causes the problem.
Thanks...
If I were you I would either download a working solution from the net and adapt it to your particular situation OR refactor the whole thing taking into consideration some SoC (Separation of Concerns).
Separate your concerns, leave the logic out of the presentation
Separate the the pagination logic from the rest. Pagination should only need to know at most 4 things to show its links
the target URL: the links need a homogeneous url scheme, only a pageNum in the url will change
how many links have to show up (probably an array of pageNums containing the variable part)
[optional] the current ID being viewed, probably to blur out a page
[optional] logic behind first/last, and behind prev/next
Help yourself by cleaning up your code and also encapsulating some functionality. For example:
function html_a($href, $content) {
return ''.$content.'';
}
function pag_href($url, $id) {
return sprintf($url,$id);// url: host/target.php?pageNum=%s&someOtherstuff...
}
// usage inside loop
echo html_a(pag_href($url,$id),$pageNum);
// if you do this right, your pagination code can become reusable
use some mysql features to your advantage. You can limit the number of results with LIMIT, set the first element of the page with OFFSET, and still get the total of number of rows with SQL_CALC_FOUND_ROWS
// This way is clearer for me
$q = 'SELECT SQL_CALC_FOUND_ROWS image_id FROM images WHERE album_id=? ORDER BY image_id DESC LIMIT ? OFFSET ?'
// after executing your query you may now use pdo's foundRows
$totalNumEntries = $pdo->foundRows();
// get number of pages with pageSize
$totalNumPages = (int)ceil($totalNumEntries / $yourPageSize);
All in all, try to practice some encapsulation/separation of concerns, do some planning ahead and you won't have to deal with code that not even you want to debug
I'm sorry this does not help with your existing code

CodeIgniter pagination always shows page 1

I already using the pagination library in nearly ten modules, with no problems, but it fails in last one (and the most important).
My routing for this section is:
$route['candidate/sort/(:any)/(:any)/page/(:num)'] = 'candidate/sort/$1/$2/$3';
My Controller
public function sort($type, $id, $page = 1) {
/* Load Config */
$data = $this->data;
$data['sub_active'] = 'candidate';
$data['type'] = $type;
/* Get Candidates */
$total = $this->candidates->getTotal($type, $id);
if(($this->limit >= $total) && ($page > 1)) {
$data['candidates'] = $this->candidates->getCandidates(1, $this->limit, $type, $id);
}elseif(((($this->limit * $page) - $this->limit) >= $total) && ($page > 1)) {
$data['candidates'] = $this->candidates->getCandidates(ceil($total / $this->limit), $this->limit, $type, $id);
}else{
$data['candidates'] = $this->candidates->getCandidates($page, $this->limit, $type, $id);
}
/* Pagination */
$this->load->library('pagination');
# Config Pagination
$data['cms']['tables']['total_rows'] = $total;
$data['cms']['tables']['per_page'] = $this->limit;
$data['cms']['tables']['first_url'] = base_url($data['sub_active'].'/sort'.'/'.$type.'/'.$id);
$data['cms']['tables']['base_url'] = base_url($data['sub_active'].'/sort'.'/'.$type.'/'.$id.'/page');
$data['page'] = $page;
$data['total_pages'] = ceil($total / $this->limit);
$data['total'] = $total;
# Initialize Pagination
$this->pagination->initialize($data['cms']['tables']);
$data['pagination'] = $this->pagination->create_links();
/* Display Template */
$this->twig->display('pages/list_candidate.htm', $data);
}
Base first url = myweb.com/candidate/sort/$type/$id and base url = myweb.com/candidate/sort/$type/$id/page
But the pagination doesn’t work, it always the same page (page 1 on this case). I'm using this same schema in other controllers and it works fine, only fails with this.
Thanks in advance.
I finally found the answer:
$config['uri_segment'] = 6;
That's because codeigniter does not detect well the URL.
Nice, I am glad you found the answer Tunnecino!
But I think its need to be further explained , why
According to our wonderful CI user guide, here is how we determine the uri_segment so not to make the same mistake again :)
$this->uri->segment(n)
Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. Segments are numbered from left to right. For example, if your full URL is this:
http://example.com/index.php/news/local/metro/crime_is_up
The segment numbers would be this:
1.news
2.local
3.metro
4.crime_is_up
By default the function returns FALSE (boolean) if the segment does not exist. There is an optional second parameter that permits you to set your own default value if the segment is missing. For example, this would tell the function to return the number zero in the event of failure:
$product_id = $this->uri->segment(3, 0);

PHP pagination problem

So for some reason I am trying to figure out why my pagination isnt working properly. I get it to move from page 1 to 2 but it wont go to page 3 for some reason. I checked to see if the query from the DB was correct and it was so not sure where I am going wrong.
$per_page = '4';
$tenure_sql = 'SELECT COUNT(id) as count
FROM people.bywu
WHERE type <> 0
AND status = "approved"';
$tenure_query = mysql_query( $tenure_sql, DB );
$tenure_count = mysql_fetch_object( $tenure_query );
$tenure_count = $tenure_count -> count;
$tenure_pages = ceil( $tenure_count / $per_page );
<div class="pagination" id="tenure_pages">
<
Stories <span id="tenure_low" class="current_low"><?= $tenure_count ? '1':'0' ?></span>-<span id="tenure_high" class="current_high"><?= $tenure_count > 4 ? $per_page : $tenure_count ?></span> of <span class="total"><?= $tenure_count ?></span>
>
<span class="pages" style="display:none;"><?= $tenure_pages ?></span>
<?
for( $i = 1; $i < $tenure_pages + 1; $i++ )
{
echo '' . $i . ' ';
} // for
?>
Scrapped away from kohana pagination class, i think you will find it useful if you know any basics about php classes.
Usage :
$pager = Pagination::factory(array('current_page' => $_GET['page'], 'total_items' => $total_items, 'items_per_page' => 20));
if ($pager->next_page) { /* etc.......*/ }
<?php
class Pagination {
protected $config = array(
'current_page' => 1,
'total_items' => 0,
'items_per_page' => 10
);
// Current page number
protected $current_page;
// Total item count
protected $total_items;
// How many items to show per page
protected $items_per_page;
// Total page count
protected $total_pages;
// Item offset for the first item displayed on the current page
protected $current_first_item;
// Item offset for the last item displayed on the current page
protected $current_last_item;
// Previous page number; FALSE if the current page is the first one
protected $previous_page;
// Next page number; FALSE if the current page is the last one
protected $next_page;
// First page number; FALSE if the current page is the first one
protected $first_page;
// Last page number; FALSE if the current page is the last one
protected $last_page;
// Query offset
protected $offset;
/**
* Creates a new Pagination object.
*
* #param array configuration
* #return Pagination
*/
public static function factory(array $config = array())
{
return new Pagination($config);
}
/**
* Creates a new Pagination object.
*
* #param array configuration
* #return void
*/
public function __construct(array $config = array())
{
// Pagination setup
$this->setup($config);
}
/**
* Loads configuration settings into the object and (re)calculates pagination if needed.
* Allows you to update config settings after a Pagination object has been constructed.
*
* #param array configuration
* #return object Pagination
*/
public function setup(array $config = array())
{
// Only (re)calculate pagination when needed
if ($this->current_page === NULL
OR isset($config['current_page'])
OR isset($config['total_items'])
OR isset($config['items_per_page']))
{
// Calculate and clean all pagination variables
$this->current_page = (int) $this->config['current_page'];
$this->total_items = (int) max(0, $this->config['total_items']);
$this->items_per_page = (int) max(1, $this->config['items_per_page']);
$this->total_pages = (int) ceil($this->total_items / $this->items_per_page);
$this->current_page = (int) min(max(1, $this->current_page), max(1, $this->total_pages));
$this->current_first_item = (int) min((($this->current_page - 1) * $this->items_per_page) + 1, $this->total_items);
$this->current_last_item = (int) min($this->current_first_item + $this->items_per_page - 1, $this->total_items);
$this->previous_page = ($this->current_page > 1) ? $this->current_page - 1 : FALSE;
$this->next_page = ($this->current_page < $this->total_pages) ? $this->current_page + 1 : FALSE;
$this->first_page = ($this->current_page === 1) ? FALSE : 1;
$this->last_page = ($this->current_page >= $this->total_pages) ? FALSE : $this->total_pages;
$this->offset = (int) (($this->current_page - 1) * $this->items_per_page);
}
// Chainable method
return $this;
}
/**
* Returns a Pagination property.
*
* #param string property name
* #return mixed Pagination property; NULL if not found
*/
public function __get($key)
{
return isset($this->$key) ? $this->$key : NULL;
}
/**
* Updates a single config setting, and recalculates pagination if needed.
*
* #param string config key
* #param mixed config value
* #return void
*/
public function __set($key, $value)
{
$this->setup(array($key => $value));
}
} // End Pagination
?>
Unless the count() you get from the database is 9 or larger, you'd never see a 3.
ceil(0/4) -> 0
...
ceil(8/4) -> 2
ceil(9/4) -> 3
So... how many articles are there in the database that match the conditions in your query?
You don't show how you're passing around the "current page" count in your code, so how does the code know which page you're on at the moment?
$total_pages = 8;
$current_page = $_GET['curPage'];
for ($i = 1; $i <= $total_pages; $i++) {
$class = ($i == $current_page) ? ' class="current"' : '';
echo <<<EOL
<a href="page.php?curPage=$i"$class>$i</a>
EOL;
}

Categories