TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
Advertisement
Associates
Associates
techtuts Darkmindz
CSS Tutorials Tutorialsphere.com - Free Online Tutorials
Boston PHP SurfnLearn
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 02-08-2008, 05:38 PM   #1 (permalink)
The Gregarious
Upcoming Programmer Inquisitive 
 
Join Date: Sep 2007
Posts: 684
Thanks: 85
Tanax is on a distinguished road
Default Pagination class

Hello.

I'm releasing my pagination class.
I already wrote it in another topic while helping someone, so I thought I'd just make an own topic for it.

I've improoved it since I posted it in that other topic, and now I've written descriptions of each function.

Also, this *should* work without MySQL, eventhough my example is based on MySQL.

php Code:
<?php

/**
||||||||||||||||||||||||||||||||||||||||||
|||| @author Tanax
|||| @copyright 2008
||||||||||||||||||||||||||||||||||||||||||
**/


    class pagination {
       
        // The total values.
        private $totalPages;
        private $totalResults;
        private $totalPerPage;
       
        // The current values.
        private $currentPage;
        private $currentSpan;
       
        // The first result on current page.
        private $firstResult;
       
        /**
         *  Sets the maximum allowed results per page
         *
         *  @param integer $max, default 10
        **/

        public function setMax($max = 10) {
           
            if(is_numeric($max)) {
               
                $this->totalPerPage = $max;
               
            }
           
        }
       
        /**
         *  Generate the first result on the current page
         *
         *  @param integer $page, which page we're currently viewing
         *  @return integer first result
        **/

        public function setPage($page) {
           
            if(is_numeric($page)) {
               
                $this->currentPage = mysql_real_escape_string($page);
                $this->firstResult = (($this->currentPage * $this->totalPerPage) - $this->totalPerPage);
               
                return $this->firstResult;
               
            }
           
        }
       
        /**
         *  Generates how many pages based on the total amount of results
         *
         *  @param array $results, an array of all the results
         *  @return array of pages
        **/

        public function getPages($results) {
           
            $this->totalResults = count($results);
            $totalPages = $this->totalResults / $this->totalPerPage;
            $this->totalPages = ceil($totalPages);
           
            $x = 1;
            $array = array();
           
            while($x <= $this->totalPages) {
               
                $array[] = $x;
                $x++;
               
            }
           
            return $array;
           
        }
       
        /**
         *  Checks if a link is valid
         *
         *  @param integer $pagenr, the number of the page you want to check if it exist
         *  @return true or false
        **/

        public function checkLink($pagenr) {
           
            if($pagenr <= $this->totalPages && $pagenr >= 1) {
               
                return true;
               
            }
           
            return false;
           
        }
       
        /**
         *  Generate the current page number
         *
         *  @return array, [0] = the current page, [1] = total pages
        **/

        public function getCurrentPage() {
           
            $array = array();
            $array[] = $this->currentPage;
            $array[] = $this->totalPages;
           
            return $array;
           
        }
       
    }

?>


Example usage:
php Code:
<?php

/**
||||||||||||||||||||||||||||||||||||||||||
|||| @author Tanax
|||| @copyright 2008
||||||||||||||||||||||||||||||||||||||||||
**/

   
    include('pagination.php');
    $p = $_GET['p'];
    (isset($p)) ? $p : 1;
    $max = 10;
   
    // Create the object and set some basic values.
    $pagination = new pagination();
    $pagination->setMax($max)
   
    // Get the total results, and then calculate how many pages that becomes based on how many results per page.
    $totSql = "SELECT * FROM `table`";
    $totQuery = mysql_query($totSql) or die(mysql_error());
    $totResults = mysql_fetch_array($totQuery);
    $totPages = $pagination->getPages($totResults);
   
    // Set the current page, and get the first result on it.
    $first = $pagination->setPage($p);
   
    // Get the results of the current page.
    $exSql = "SELECT * FROM `table` LIMIT $first, $max";
    $exQuery = mysql_query($exSql) or die(mysql_error());
    $exResults = mysql_fetch_array($exQuery);
   
    // Echo out the current page, and the total amount of pages.
    $page = $pagination->getCurrentPage();
    echo 'Page: '.$page[0].' of '.$page[1];
   
    // Get previous page link, and check if it's valid.
    $prevLink = $p - 1;
    if($pagination->checkLink($prevLink)) {
       
        echo '<a href="example.php?page='.$prevLink.'">Previous Page</a>';
       
    }
   
    // Print all the pages
    foreach($totPages as $pageNumber) {
       
        if($pageNumber == $p) {
           
            // The markup for showing that this is the current page is currently <strong>
            echo '<a href="example.php?page='.$pageNumber.'"><strong>'.$pageNumber.'</strong></a>';
           
        }
       
        else {
           
            echo '<a href="example.php?page='.$pageNumber.'">'.$pageNumber.'</a>';
           
        }
       
    }
   
    // Get the next page link, and check if it's valid.
    $nextLink = $p + 1;
    if($pagination->checkLink($nextLink)) {
       
        echo '<a href="example.php?page='.$nextLink.'">Next Page</a>';
       
    }
   
    foreach($exResults as $news) {
       
        echo $news['news_title'];
        echo '<br /><br />';
       
    }
   

?>


I started working on an example to use this with a gallery, where the image files were in a image dir. But I got stuck.
More specificly I got stuck when I was trying to get the results within the first result on a page, and the last result on a page, based on the value of the max nr of results per page.
Maybe someone else can try to work it out?

Anyways, this is my pagination class.
Any comments?
__________________
Tanax is offline  
Reply With Quote
The Following 2 Users Say Thank You to Tanax For This Useful Post:
Alan @ CIT (02-08-2008), codefreek (10-31-2008)
Old 02-08-2008, 06:32 PM   #2 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 714
Thanks: 2
Salathe is on a distinguished road
Default

An example which uses a directory of images is given below. The folder structure is such that we have an images folder and within that a thumbs folder. Filenames match between the folders representing a thumbnail and full-sized version of the same image. It's up to you to create the thumbnails however you like.

PHP Code:
<?php

include('pagination.php');
$p = (isset($_GET['p']) AND ctype_digit($_GET['p']) AND (int) $_GET['p'] > 0
   ? (int) 
$_GET['p'
   : 
1;
$max 10;

// Create the object and set some basic values.
$pagination = new pagination();
$pagination->setMax($max);

// Set up some directory variables 
$dir    dirname(__FILE__).'/images/';
$webdir 'images/';
$thdir  'images/thumbs/';

// Grab all of the images 
$images glob($dir.'*.jpg');

// Set up pagination variables
$totPages  $pagination->getPages($images);
$first     $pagination->setPage($p);
$page      $pagination->getCurrentPage();

// Only select the portion of the images array 
// that represents our page
$exResults array_slice($images$first$max);

// Make links spaced a bit
echo '
<style type="text/css">
a { margin: 0 2px 0 0; }
</style>'
;

// Start pagination display
printf('Page: %d of %d | '$page[0], $page[1]);
$pagination->checkLink($p 1) AND printf('<a href="?p=%d">Previous Page</a>'$p 1);
foreach (
$totPages as $pageNumber)
{
    
$tpl = ($pageNumber == $p)
         ? 
'<a href="?p=%1$d">%1$d</a>'
         
'<a href="?p=%1$d"><strong>%1$d</strong></a>';
    
printf($tpl$pageNumber);
}
$pagination->checkLink($p 1) AND printf('<a href="?p=%d">Next Page</a>'$p 1);

// Display current page of images 
echo '<hr><div class="images">';
foreach(
$exResults as $image)
{
    
$image str_replace($dir$webdir$image);
    
$thumb str_replace($webdir$thdir$image);
    
printf('<a href="%s" style="margin: 0 5px 5px 0;"><img src="%s" alt="%s"></a>',
           
$image$thumbbasename($image));
}
echo 
'</div>';
It's just a very quick example essentially ported over from the MySQL example posted above. Don't shoot me if it doesn't work!
__________________
Salathe is offline  
Reply With Quote
The Following 3 Users Say Thank You to Salathe For This Useful Post:
Alan @ CIT (02-08-2008), codefreek (10-31-2008), Tanax (02-08-2008)
Old 02-08-2008, 06:48 PM   #3 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 482
Thanks: 51
Alan @ CIT is on a distinguished road
Default

Thanks guys, very handy

Alan
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
Old 02-08-2008, 07:01 PM   #4 (permalink)
The Gregarious
Upcoming Programmer Inquisitive 
 
Join Date: Sep 2007
Posts: 684
Thanks: 85
Tanax is on a distinguished road
Default

Quote:
Originally Posted by Salathe View Post
An example which uses a directory of images is given below. The folder structure is such that we have an images folder and within that a thumbs folder. Filenames match between the folders representing a thumbnail and full-sized version of the same image. It's up to you to create the thumbnails however you like.

PHP Code:
<?php

include('pagination.php');
$p = (isset($_GET['p']) AND ctype_digit($_GET['p']) AND (int) $_GET['p'] > 0
   ? (int) 
$_GET['p'
   : 
1;
$max 10;

// Create the object and set some basic values.
$pagination = new pagination();
$pagination->setMax($max);

// Set up some directory variables 
$dir    dirname(__FILE__).'/images/';
$webdir 'images/';
$thdir  'images/thumbs/';

// Grab all of the images 
$images glob($dir.'*.jpg');

// Set up pagination variables
$totPages  $pagination->getPages($images);
$first     $pagination->setPage($p);
$page      $pagination->getCurrentPage();

// Only select the portion of the images array 
// that represents our page
$exResults array_slice($images$first$max);

// Make links spaced a bit
echo '
<style type="text/css">
a { margin: 0 2px 0 0; }
</style>'
;

// Start pagination display
printf('Page: %d of %d | '$page[0], $page[1]);
$pagination->checkLink($p 1) AND printf('<a href="?p=%d">Previous Page</a>'$p 1);
foreach (
$totPages as $pageNumber)
{
    
$tpl = ($pageNumber == $p)
         ? 
'<a href="?p=%1$d">%1$d</a>'
         
'<a href="?p=%1$d"><strong>%1$d</strong></a>';
    
printf($tpl$pageNumber);
}
$pagination->checkLink($p 1) AND printf('<a href="?p=%d">Next Page</a>'$p 1);

// Display current page of images 
echo '<hr><div class="images">';
foreach(
$exResults as $image)
{
    
$image str_replace($dir$webdir$image);
    
$thumb str_replace($webdir$thdir$image);
    
printf('<a href="%s" style="margin: 0 5px 5px 0;"><img src="%s" alt="%s"></a>',
           
$image$thumbbasename($image));
}
echo 
'</div>';
It's just a very quick example essentially ported over from the MySQL example posted above. Don't shoot me if it doesn't work!
Thanks
And thanks for moving it

Well, I'm glad that it seems to work without MySQL aswell, because that was my intention, to not just limit the class to a MySQL based pagintion
__________________
Tanax is offline  
Reply With Quote
Old 02-11-2008, 03:17 PM   #5 (permalink)
The Contributor
 
Gibou's Avatar
 
Join Date: Nov 2007
Location: France, near Paris
Posts: 48
Thanks: 6
Gibou is on a distinguished road
Default

I just see a bad thing in your class. To use it, you have to keep your mysql connexion opened all the time your page is loading. It's not safe or optimized if the display of your current page is heavy/long :)

Whatever, indeed, it's useful :)
Send a message via MSN to Gibou
Gibou is offline  
Reply With Quote
Old 10-31-2008, 05:02 PM   #6 (permalink)
The Wanderer
 
Join Date: Oct 2008
Posts: 9
Thanks: 0
kjarli is on a distinguished road
Default

Finally someone that doesn't mix up sql with pagination, good job!
kjarli is offline  
Reply With Quote
Old 10-31-2008, 06:15 PM   #7 (permalink)
Moderator
Inquisitive 
 
codefreek's Avatar
 
Join Date: Sep 2007
Location: Near you.
Posts: 452
Thanks: 228
codefreek is on a distinguished road
Default

nice work ;) learned some new things ;) ty!
__________________
inquisitive
1. Eager to acquire knowledge.
2. Too curious; overly interested; nosy.
codefreek is offline  
Reply With Quote
Old 10-31-2008, 09:47 PM   #8 (permalink)
The Gregarious
Upcoming Programmer Inquisitive 
 
Join Date: Sep 2007
Posts: 684
Thanks: 85
Tanax is on a distinguished road
Default

Quote:
Originally Posted by Gibou View Post
I just see a bad thing in your class. To use it, you have to keep your mysql connexion opened all the time your page is loading. It's not safe or optimized if the display of your current page is heavy/long :)

Whatever, indeed, it's useful :)
Yea.. or well, not really. You can close it after each query, it's not like you have to use a cache or anything to keep it working.. or did I misunderstand what you meant?

Thank you

Quote:
Originally Posted by kjarli View Post
Finally someone that doesn't mix up sql with pagination, good job!
Thank you! I thought about that too, and I felt the urge that someone needed to do this.

Thanks again

Quote:
Originally Posted by codefreek View Post
nice work ;) learned some new things ;) ty!
Thank you! Glad you learned something
__________________
Tanax is offline  
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 01:40 AM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0