ncoded contact information

website design services web design service online shops service optimisation and seo services graphical design servicese-commerce service search engines services graphic design services

PHP 5 Pagination (for multiple result pages)

Posted by admin On May - 15 - 2009

Pagination refers to spliting a number of pages using a ‘page 1 of N pages’ type menu. Pagination is the actual process of spliting the number of returned items into ‘pages’.

A very simple way to establish pagination on a website is to use the new PHP 5 function scandir() to build an array, and then use this array within a loop to build up your pagination.

You can view the code to establish this pagination functionality below:

//read all the files in a given directory into an array
$arrray_of_all_files = scandir('/directory/');

Now in most cases (linux etc) within a directory you will find system files (such as .httacess etc files). Therefore in order to only get the non-system files we will setup a condition to elminate these files.

//init new array
$files_req = array();

//only add a file if it does not begin with a dot (.)

foreach(arrray_of_all_files as $N){
	if(strpos($N,'.')!==0){
		array_push($files_req,$N);
	}
}

In order to paginate the results within the array we need to establish how many items per page we require, as well as how many pages - although this of course makes the applicability static - so in real world examples the pages would be of course be dictated by the items per page.

The main function that we use to work this out is the PHP function array_chunk(). This function is very simple and just takes two parameters (arguments) - the array you want to split and the number of elements in each section (page).

//create a multdimensional array, holding each set of elements
//eg [0] holds first set, [1] holds second set, etc.
$sets = array_chunk($files_req, 25);

Now all we need to do is interate through the array building up some pagination links - obviously the page that gets linked will need to know which set to use, and have the code to format (display) these.

$link_code_start="<a href='page.php?set=";
$link_code_finish=$i."'".">";
for($i=1; $i<count($sets)+1; $i++){
     echo $link_code_start.$i.$link_code_finish;
}
  • Share/Save/Bookmark

Other related resources that may be of interest to you

Comments are closed.

Website & E-Commerce Solutions


nCoded Website, IP & Content © 2003 - 2009 nCoded - All Rights Reserved - No part of this website may be reproduced without permission.