PHP
  Home arrow PHP arrow Page 3 - Previous or Next? Paginating Records with PHP, part 1
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 1
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 22
    2005-04-26


    Table of Contents:
  • Previous or Next? Paginating Records with PHP, part 1
  • The first step: paginating records in a procedural way
  • A deeper look at the "paginatetRecords()" function
  • Putting the "paginateRecords()" function into action: procedural record paging

  • 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 1 - A deeper look at the "paginatetRecords()" function
    ( Page 3 of 4 )

    First, the function accepts three parameters, in the following order: the text file from which we're retrieving data, the page pointer that indicates the current page to be viewed, and finally the number of records per page to be displayed, according to our paginating criteria. In this case, I've assigned a default value of 5, so the total records should be displayed in chunks of five at once, and then provide the proper paginating links.

    Still with me? Okay, now the function initializes the $output variable that will store the formatted records and the links to be displayed in the browser. The next step involves validating each of the parameters passed to the function. First, the function checks whether there is a valid data source text file. If it exists, then the file is read in reverse order, assuming that the most recent entry in our song file is the last line of the file. Otherwise, if no data file is found, the function stops the execution by calling a die() statement.

    The next parameter to be validated is the number of records per page. If this value is a positive integer, it's assigned to the $numRecs variable. Otherwise, the function kills the script with a call to die(). Nothing unexpected, right?

    Finally, the function calculates the number of pages needed to display all of the records, dividing the total of records by the number of records per page. Remember, it's simple mathematics. Once this value has been calculated, we need to validate the $page variable, for avoiding having it tampered with directly from the query string -- just in case someone with malicious thoughts tries to make the script crash or to inject improper code straight into the function. The ancient principle is always present: trust no one!

    The process for validating the function parameters is done with the following lines:

    // validate data file

    (file_exists($dataFile))?$data=array_reverse(file
    ($dataFile)):die('Data file not valid.');

    // validate number of records per page

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

    // calculate total of records

    $numPages=ceil(count($data)/$numRecs);

    // validate page pointer

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

    $page=1;

    }

    By this point, the function has validated its parameters, and it's ready to get the records from the data file. Since data is now stored in the $data array, the task of retrieving the records according to the current page is quite simple. Using the handy "array_slice()" PHP built-in function to move the internal array pointer to the desired place and get a specific number of elements, makes it really simple obtain the corresponding records. That's what we do with the expression:

    $data=array_slice($data,($page-1)*$numRecs,$numRecs);

    As you can see, if we're at the first page ($page=1), the first five array elements are obtained. In a similar way, for the second page ($page=2), the second set of five elements is retrieved, and so on. This simple expression is very powerful, since it is allowing us to navigate trough the array structure with no big hassles.

    Now that the function has stored the corresponding records, all that it needs to do is loop over them to get the proper values. First we iterate over each line of the $data array (considered as a row), and next over the columns (or fields) of that element. Remember that we've defined our data file with two columns separated by a pipe character, so we explode each line into columns. The process ends up applying some basic formatting to the values and adding them to the $output variable, but this might be easily changed to define a more polished look. The loop process is performed with the lines:

    // append records to output

    foreach($data as $row){

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

    foreach($columns as $column){

    $output.=$column.'&nbsp;';

    }

    $output.='<br />';

    }

    Happily, our required records are stored in the $output variable. Half of the job is already done. We need to create the paging links to make the script fully functional. In order to build the links, the function checks whether it's possible to generate a <previous> link, in the following manner:

    // create previous link

    if($page>1){

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

    }

    If the page pointer is greater than 1, it means that we're not on the first page, so we append a previous link to the final output. With our previous link generated, we need to look at the intermediate links, which are created with this simple loop:

    for($i=1;$i<=$numPages;$i++){

    ($i!=$page)?$output.='<a href="'.$_SERVER
    ['PHP_SELF'].'?page='.$i.'">'.$i.'</a>&nbsp;':$output.=$i.'&nbsp;';

    }

    Please notice that the snippet displays the page numbers, appending the $page variable to each link created with the $_SERVER['PHP_SELF'] predefined variable, and doesn't generate any link when it detects the current page.

    The final step consists of creating the <next> link, whenever possible. If the page pointer is less than the number of pages, the next link is appended to the final output. The function creates this link with the lines:

    // create next link

    if($page<$numPages){

    $output.='&nbsp;<a href="'.$_SERVER['PHP_SELF'].'?
    page='.($page+1).'">Next&gt;&gt;</a> ';

    }

    Good! We're retrieving a specified number of records and creating those desired page links. With a few lines of code, we can offer that functionality on our site to pleased users. Indeed, we're headed in the right direction. But, let's no waste more time congratulating ourselves, and put this function into action.



     
     
    >>> 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