Paging

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
phpcoder
Forum Contributor
Posts: 158
Joined: Sat Nov 02, 2002 1:18 pm
Location: Manchester, UK

Paging

Post by phpcoder »

Hi,

Can anyone give me some idea how to do paging on website.
Thanks
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Paging

Post by onion2k »

There are hundreds of topics on here that discuss it. Try searching.
ianhull
Forum Contributor
Posts: 310
Joined: Tue Jun 14, 2005 10:04 am
Location: Hull England UK

Re: Paging

Post by ianhull »

Here is a little class file which does the job just fine for me :)

Code: Select all

 
 
class Pager
   {  
       function getPagerData($numHits, $limit, $page)  
       {  
           $numHits  = (int) $numHits;  
           $limit    = max((int) $limit, 1);  
           $page     = (int) $page;  
           $numPages = ceil($numHits / $limit);  
 
           $page = max($page, 1);  
           $page = min($page, $numPages);  
 
           $offset = ($page - 1) * $limit;  
 
           $ret = new stdClass;  
 
           $ret->offset   = $offset;  
           $ret->limit    = $limit;  
           $ret->numPages = $numPages;  
           $ret->page     = $page;  
 
           return $ret;  
       }  
   }  
 
    $page = $_GET['page'];  
    $limit = 20;//set how many records you want to show
    $result = mysql_query("select count(*) FROM tableName");  
    $total = mysql_result($result, 0, 0);  
 
    // work out the pager values  
    $pager  = Pager::getPagerData($total, $limit, $page); 
    $offset = $pager->offset;  
    $limit  = $pager->limit;  
    $page   = $pager->page;  
 
    // use pager values to fetch data
    $query = "SELECT * FROM tableName LIMIT $offset, $limit";
     
    $result = mysql_query($query);
  
    while ($line = mysql_fetch_array($result))    
    {
    extract($line);
 
    echo '';//your content
 
    };//end while
    
    // output paging system (could also do it before we output the page content)  
    for ($i = 1; $i <= $pager->numPages; $i++) {  
        echo ' ';  
        if ($i == $pager->page)  
            echo 'Page '.$i.'';
        else
            echo '<a href="'.$_SERVER['SCRIPT_NAME'].'/?page='.$i.'">Page '.$i.'</a>';  
    };
    
 
Post Reply