Home arrow PHP arrow Page 3 - Previous or Next? Paginating Records with PHP, part 1

A deeper look at the "paginatetRecords()" function - PHP

Putting all of your content for a particular file on one page can be very user unfriendly to website visitors. Nobody likes to be confronted by a tiny vertical scroll bar! In this article, the first in a series, you will learn a simple way to paginate records from a text file using PHP.

TABLE OF CONTENTS:
  1. Previous or Next? Paginating Records with PHP, part 1
  2. The first step: paginating records in a procedural way
  3. A deeper look at the "paginatetRecords()" function
  4. Putting the "paginateRecords()" function into action: procedural record paging
By: Alejandro Gervasio
Rating: starstarstarstarstar / 23
April 26, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

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: