HomePHP Page 2 - Previous or Next? Paginating Records with PHP, part 1
The first step: paginating records in a procedural way - 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.
Our first method for paginating records might be easily developed by taking a procedural approach: using a flat text file as the data source for displaying information, and defining a PHP function that takes care of paginating the records. Sounds like something good to deploy, at least for the initial step, right?
Let's begin defining a simple text file, which contains several lines (our records), including information about a song's author and the song's title. The example file, which is called "data.dat," could be structured as listed below:
Chariots of fire|Vangelis
Friends of Mr. Cairo|Vangelis
Lucifer|The Alan Parson Project
The eye in the sky|Alan Parson Project
The turn of a friendly card|The Alan Parson Project
One and One|Robert Miles
Cherry Blossom Girl|Air
Hot stuff|Donna Summer
Bad Girls|Donna Summer
I will survive|Gloria Gaynor
Rimes and reasons|John Denver
Touch and go|Emerson,Lake and Powell
In Jeopardy|Roger Hogdson
As you can see, our text file containing information about several songs has been created, defining two fields for each line, author and title respectively, separated by a pipe ("|") character. This way we've established the overall structure for this simple flat database. Please don't start complaining about my musical preferences, because they're beyond the scope of this article. Let's focus our attention on the code listed above.
Once we have defined the data source file, we need to create a PHP function for retrieving the records from the file, and generating the corresponding paginating links. In fact, the process is pretty straightforward, as we'll see in a moment. Now, let's start writing the function to paginate records. I've named it "paginateRecords()", and its definition is the following:
// 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);
Don't feel intimidated by the function's source code, since it's really easy to understand. In order to grasp the underlying logic, let's break down the code to have a detailed look at each section. Are you ready? Let's go for it.