Home arrow PHP arrow Page 2 - Previous or Next? Paginating Records with PHP, part 4

A quick look at the class source code - PHP

In the fourth and final article in our series about paginating records with PHP, we will look at the source code for the "pager" PHP class we developed in part three, and show several examples to demonstrate possible uses in production environments.

TABLE OF CONTENTS:
  1. Previous or Next? Paginating Records with PHP, part 4
  2. A quick look at the class source code
  3. Creating the database table
  4. Paging MySQL records: putting the "Pager" class into action
  5. Extending the use of the "Pager class": more examples to come
By: Alejandro Gervasio
Rating: starstarstarstarstar / 16
May 17, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: