How do I implement a custom "paging" script for a variable number of items?

A very common problem in web programming is to implement paging. Paging is required whenever there is an undefined amount of items (usually queried from a database) with a maximum amount of items to be displayed on one page. If there is more than one page, there must be a possibility to navigate through these pages while each page displays the desired amount of items. An example will demonstrate the problem: State: - You have a category containing 23 products to be displayed in the category overview of your webshop - A single page should display a maximum of 8 pages for design and usability reasons Now we have to calculate the number of pages, the number of products to display per page and display everything to the user. This case will result in 3 pages: Page 1 will display the items 1-8, Page 2 will display the pages 9-16 and Page 3 will display the items 17-23. Please show a general algorithm for this problem.
1 answer

How to implement a custom paging script for a variable number of items (incl. PHP sample script)

Will explain the solution to this problem with using a code written in PHP (you should be able to adapt this for other programming languages quite easily).

// first of all, we need the total number of all items to display (in the example this would be 23), usually a database count statement will give this number
$resultsOverall = 0;

// enter the maximum number of items per page here
$resultsPerPage = 10;

// the number of the current page (e.g. page 2 display items 9-16 in the example)
$pageNumber = 1;

// the current number is usually determined dynamically, that means we have to check which page we need to display
if(isset($_REQUEST["pageNumber"]) && $_REQUEST["pageNumber"] > 1) {
$pageNumber = $_REQUEST["pageNumber"];
}

/**** The logic ****/

// determine the first result to show (on example page 2 this will be 9)
$resultsFrom = ($pageNumber*$resultsPerPage-$resultsPerPage+1);

// determine the last result to show (on example page 2 this will be 16)
$resultsTo = ($resultsFrom-1)+$resultsPerPage;

// if the number of results to is bigger than the number of results overall, cut it (e.g. on example page three $resultsTo would be 24, but $resultsOverall would be 23, therefore it is cut)
if($resultsTo > $resultsOverall) {
$resultsTo = $resultsOverall;
}

// as a last step we have to determine the number of pages
$allPages = ceil($resultsOverall / $resultsPerPage);

// now we could proceed with some query ("SELECT * FROM items LIMIT $resultsFrom, $resultsTo") and display anything we need

Taggings: