PHP
  Home arrow PHP arrow Page 2 - Previous or Next? Paginating Records with PHP, part 4
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

Previous or Next? Paginating Records with PHP, part 4
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 14
    2005-05-17


    Table of Contents:
  • Previous or Next? Paginating Records with PHP, part 4
  • A quick look at the class source code
  • Creating the database table
  • Paging MySQL records: putting the "Pager" class into action
  • Extending the use of the "Pager class": more examples to come

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Previous or Next? Paginating Records with PHP, part 4 - A quick look at the class source code
    ( Page 2 of 5 )

    Before we try the class and show a real example, it's necessary to list its full code. This way, you'll have an overall conception of how it works. Here's the complete source code for the "Pager" class:

    <?php
    /*
    * PHP Pager class
    * @access public
    */

    class Pager {
      /**
      * MySQL connection identifier
      * @access private
      * data type string
      */
      var $conId;

     

      /**
      * SQL query
      * @access private
      * data type string
      */
      var $query;

     

      /**
      * number of records per page
      * @access private
      * data type integer
      */
      var $numRecs;

     

      /**
      * generated output for records and paging links
      * @access private
      * data type string
      */
      var $output;

     

      /**
      * records template file
      * @access private
      * data type string
      */
      var $template;

     

      /** ID attribute for styling paging links
      * @access private
      * data type string
      */
      var $linksId;

     

      /**
      * Pager constructor
      * @access public
      * @param string conId
      * @param string query
      * @param string linksId
      * @param integer numRecs
      * @param string template
      */
      function Pager (&$conId,$query,$linksId,$numRecs=10,
                     $template='default_record_template.htm'){

        // validate connection idenfifier
        (mysql_query('SELECT 1',&$conId))?$this->conId=
         &$conId:die('Invalid connection identifier.');

        // validate query
        (preg_match("/^SELECT/",$query))?$this->query=
         $query:die('Invalid query '.$query);

        // validate paging links ID
        (!is_numeric($linksId))?$this->linksId=
         $linksId:die('Invalid ID for paging links '.$linksId);

        // validate template file
        (file_exists($template))?$this->template=
         $template:die('Invalid template file '.$template);

        // validate number of records per page
        (is_int($numRecs)&&$numRecs>0)?$this->numRecs=
          $numRecs:die('Invalid number of records '.$numRecs);

        // initialize output
        $this->output='';

      }

     

      /**
      * method displayRecords
      * @access public 
      * @return string output
      * @param integer page
      * @description display paginated records/paging links
      */
      function displayRecords($page){

        // calculate total number of records
        if(!$totalRecs=mysql_num_rows(mysql_query($this->query))){
          die('Cannot retrieve records from database');
        }

        // calculate number of pages
        $numPages=ceil($totalRecs/$this->numRecs);
        if(!preg_match("/^\d{1,2}$/",$page)||
           $page<1||$page>$numPages){
          $page=1;
        }

        // get result set
        $result=mysql_query($this->query.' LIMIT '.($page-1)*$this->numRecs.','.$this->numRecs);

        // read template file
        $templateContent=file($this->template);

        // append template file footer to final output
        $this->output=reset($templateContent);

        // move pointer to placeholder line
        $templateRow=next($templateContent);

        // replace placeholders with actual data
        while($row=mysql_fetch_row($result)){
          $tempOutput=$templateRow;
          for($i=0;$i<mysql_num_fields($result);$i++){
             $tempOutput=str_replace('{data'.$i.'}',
              $row[$i],$tempOutput);
          }

          // remove unpopulated placeholders
          $this->output.=preg_replace("/{data.}/",'',$tempOutput);

        }

        // append template file footer to final output
        $this->output.=end($templateContent);

        // create page links
        $this->output.='<div id="'.$this->linksId.'">';

        // create previous link
        if($page>1){
          $this->output.='<a href="'.$_SERVER['PHP_SELF'].'?page='.
          ($page-1).'">&lt;&lt;Previous</a>&nbsp;';
        }

        // create numerated links
        for($i=1;$i<=$numPages;$i++){
          ($i!=$page)?$this->output.='<a href="'.$_SERVER['PHP_SELF']
           .'?page='.$i.'">'.$i.'</a>&nbsp;':
           $this->output.=$i.'&nbsp;';
        }

        // create next link
        if($page<$numPages){
          $this->output.='&nbsp;<a href=
          "'.$_SERVER['PHP_SELF'].'?page=
           '.($page+1).'">Next&gt;&gt;</a> ';
        }
        $this->output.='</div>';

        // return final output
        return $this->output;

      }

    }

    ?>

     

    That was a long listing, don't you think? However, it's really worthwhile. Now we're ready to develop some examples and see the class in action. Since the class will work with the MySQL server, let's begin by setting up a sample database and creating a basic table with some records. Want to know more? Just click the link and keep reading.



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Adding Ordering and Grouping Clauses to the ...
    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek