HomePHP Page 2 - Previous or Next? Paginating Records with PHP - Part 2
Taking the procedural approach: the friendly "paginateRecords()" function - PHP
In the first article in this series, we learned how to do simple pagination of records taken from a text file. In this article, we will look at pagination for a larger group of records, using an Objected Oriented rather than a procedural approach to creating the application.
In the first article, we defined a simple text file for storing information, where each line is considered a single record, and each column is a different field. In programming environments, this is known as a flat database. We went as far as setting up a rather basic function to paginate data retrieved from a text file. The function's source code was originally defined as shown below:
// 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);
Although the function is basic, it's really flexible and portable, because it allows us to specify a data file to read from, and the number of records (in this case we're referencing file lines and not true database records) to be displayed at a time. Also, it's powerful enough to generate the classic <previous> - 1, 2, 3 …<next> navigational links. It's an elemental format, but with minor modifications, it might be changed to present a more polished look, just by tweaking the original code.
One possible implementation for the function may be defined in the following example:
In the above example, we've specified a data file "data1.dat" from which to read, and a default value of five records to be displayed at a time. Because of its flexibility, another case may be coded as follows:
The previous case will display data from a "data2.dat" file and show ten records per page, reordering the paging links according to the new parameters. Definitely, we have to agree that our function is very versatile and extendable. Just play around with the code to make it fit your needs.
While the function is handy for small projects, it lacks some of the complexities found in more sophisticated applications. Therefore, as I previously stated, we're going to develop a PHP class that will paginate records from a data file. It will keep the functionality of the initial procedural method, but offer the wide advantages inherent to Object Oriented Programming. So, let's start defining the PHP class.