PHP
  Home arrow PHP arrow Page 6 - Previous or Next? Paginating Records w...
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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? 
PHP

Previous or Next? Paginating Records with PHP - Part 2
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 8
    2005-05-03

    Table of Contents:
  • Previous or Next? Paginating Records with PHP - Part 2
  • Taking the procedural approach: the friendly "paginateRecords()" function
  • Taking the OOP approach: defining the "Pager" PHP class
  • Defining the "displayRecords()" method
  • Source code ahead: completing the "displayRecords()" method
  • Pager class implementation

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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 2 - Pager class implementation


    (Page 6 of 6 )

    With the class completely defined, it's easy to implement a couple of examples to show how it can used. However, let's first show the complete list for our Pager class. This is the full source code:

    class Pager {

    var $output='';

    var $totalRecs;

    var $numRecs;

    function Pager($dataFile,$numRecs=5){

    // validate data file

    (file_exists($dataFile)&&count(file($dataFile))>0)?
    $this->totalRecs=array_reverse(file($dataFile)):die
    ('Data file not valid.');

    // validate number of records per page

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

    }

    function displayRecords($page){

    // calculate number of pages

    $numPages=ceil(count($this->totalRecs)/$this->numRecs);

    // validate page pointer

    if(!preg_match("/^\d{1,2}$/",$page)
    ||$page<1||$page>$numPages){

    $page=1;

    }

    // retrieve corresponding records from flat file

    $records=array_slice($this->totalRecs,($page-1)*$this-
    >numRecs,$this->numRecs);

    foreach($records as $row){

    $columns=explode('|',$row);

    foreach($columns as $column){

    $this->output.=$column.'&nbsp;';

    }

    $this->output.='<br />';

    }

    // create previous link

    if($page>1){

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

    }

    // create intermediate 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> ';

    }

    // return final output

    return $this->output;

    }

    }

    Having listed the complete class code, we can show our first example, which is presented in the following way:

    require_once('pagerclass.php');

    $pager=&new Pager('data.dat');

    $page=$_GET['page'];

    echo $pager->displayRecords($page);

    That's it. With four lines of code, we're displaying records from the text file "data.dat" and displaying the corresponding paging links, using a default value of five records per page.

    If that's not good enough for you, here's another example, showing records from a text file "data2.dat", in sets of 10 records at a time:

    require_once('pagerclass.php');

    $pager=&new Pager('data2.dat',10);

    $page=$_GET['page'];

    echo $pager->displayRecords($page);

    Our newly developed class is very flexible and portable, and easy to implement in different situations, simply by changing the parameters passed to it. As usual, feel free to play with the code and tweak it to fit your particular needs. Certainly, the possibilities are numerous.

    Summary

    In this second part, we've developed in a step-by-step process, a PHP class to paginate records in websites. Noticeably, we've branched out to an OOP approach to illustrate the great advantages that classes offer to PHP programmers. However, before you start clamoring for more complex paginating solutions, we're not done yet.

    In its current incarnation, the class lacks many desirable features that should be present in real-world applications. The first clear issue is that we're working with text files as a data source. If we're going to work with medium to large sites, we'll quickly encounter a relational database system. The second problem is the basic mechanism presented to apply some kind of visual format to the records. Thus, all of these relevant topics should be properly addressed without modifying the inner structure of the class, while maintaining the basics of the original code.

    In the third part of this series, we'll apply some interesting improvements to the class, making it possible to work directly with MySQL, offering a flexible mechanism for defining the records' visual presentation. What more can we ask for? In the meantime, have some fun playing with the class. See you soon!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · This second article transits the OOP approach to build up a class to paginate data...
       · Thanks and congratulations for your articles...i was expecting this 2nd part... i...
       · Thanks a lot for the compliments about the articles. If you have found useful this...
       · Great! While waiting for the 3rd part, i'm going to 'train' php by modifying the...
       · Thanks for the comments. I'm glad you to develop your own paging solution. Just go...
       · Where you are paging by 10 records should that be... ...
       · We made the changes to the code.Thanks,Editorial Staff.
       · Yes, that was already pointed before as you can see in previous posts, and it was...
     

       

    PHP ARTICLES

    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...
    - Working with the Email Class in Code Igniter





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway
    Stay green...Green IT