HomePHP Page 4 - Previous or Next? Paginating Records with PHP - Part 2
Defining the "displayRecords()" method - 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.
The "displayRecords()" method is the workhorse of the class, and accepts one parameter, $page, which determines which page of the retrieved records we want to see. So, let's start by defining its signature and then explain how it works:
As I said previously, the method accepts the $page parameter, which is the page pointer to determine which page we wish to view. However, before any validation process takes place, it calculates the number of pages needed to display the complete number of records. This value is obtained with the following lines:
Here we're dividing the total number of records read from the file by the number of records per page. Using ceil(), we round a decimal number up; in this way 3.25 becomes 4. Doing so, we get an integer value as the number of pages to be used.
Having obtained the number of pages, the method is now capable of validating the $page parameter. Maybe you're asking… why should I check out the validity of this parameter? The answer is that we don't want this value to be tampered with by external code. We're using the same technique shown in the first article. It's really funny to see how many websites fail to validate page pointers, and end up modifying paging links according to code injected through the querystring, even if they're using a URL rewriter. We don't want this to happen, so the method checks if the $page pointer is valid, like this: