PHP: Pagination Class

How to script a pagination class
This class makes it possible to list a number of items on several pages. It comes with a navigation of a set of links, and you also have the option to define how much span that navigation should have.

Hello!

This is a basic pagination class, coded in PHP.

Usage:
This class makes it possible to list a number of items on several pages. It comes with a navigation of a set of links, and you also have the option to define how much span that navigation should have.

So let’s get started!

The first thing we have to do, is telling PHP that we want to create a class.

1
2
3
4
5
	class pagination {
 
        // This is where our class content will be.
 
	}

So, what could be good names for variables, and how many do we need?
Well, since this pagination class should work in all ways, and not just with a mysql database, we cannot use any mysql queries inside the class. That will be done outside of the class. The class main function is just to calculate how many pages, and return those in an array.

INT: $totalPages - This is the total amount of pages. This is based on how many results per page, and how many results.
INT: $totalResults - This is the total amount of results.
INT: $totalPerPage - This is how many results per page we want. This is set before you calculate how many pages.
INT: $currentPage - The value of the current page that the user is viewing.
INT: $firstResult - The value of the first result on the current page. This is calculated within the class.

So, that’s the variables I want to use for this. It’s quite simple, it’s not alot of variables, and they’re pretty easy to understand what they do.

Next thing we need to do, is to figure out what functions we need.

  1. 1 function to set $totalPerPage
  2. 1 function to set the value of $currentPage
  3. 1 function to calculate how many pages, and return those
  4. 1 function to check if a pagenumber exists within the array of pages. This is used for next and previous links.
  5. And 1 function to get the value of $currentPage and $totalPages in an array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
	class pagination {
 
		// The total values.
		private $totalPages;
		private $totalResults;
		private $totalPerPage;
 
		// The current values.
		private $currentPage;
 
		// The first result on current page.
		private $firstResult;
 
		/**
		 *	Sets the maximum allowed results per page
		 *
		 *	@param integer $max, default 10
		**/
		public function setMax($max = 10) {
 
		}
 
		/**
		 *	Generate the first result on the current page
		 *
		 *	@param integer $page, which page we're currently viewing
		 *	@return integer first result
		**/
		public function setPage($page) {
 
		}
 
		/**
		 *	Generates how many pages based on the total amount of results
		 *
		 *	@param array $results, an array of all the results
		 *	@return array of pages
		**/
		public function getPages($results) {
 
		}
 
		/**
		 *	Checks if a link is valid
		 *
		 *	@param integer $pagenr, the number of the page you want to check if it exist
		 *	@return true or false
		**/
		public function checkLink($pagenr) {
 
		}
 
		/**
		 *	Generate the current page number
		 *
		 *	@return array, [0] = the current page, [1] = total pages
		**/
		public function getCurrentPage() {
 
		}
 
	}

So, those are our functions. As you see, all the variables are private. This is done for added security, because the only way now to access a value of one of the variables, is by calling them INSIDE the class.

PHP Tip: Always use private for variables in classes, unless you REALLY need them to be public.

Let’s take a look at the first function. It’s a really basic function, because it’s just supposed to assign a value to a variable. However, this value needs to be an integer, thus:

1
2
3
4
5
6
7
8
9
		public function setMax($max = 10) {
 
			if(is_numeric($max)) {
 
				$this->totalPerPage = $max;
 
			}
 
		}

$max is a value that’s used when calling the function.
We simply check if it’s numerical(integer), and if it is, we asign the value of $max, to the variable private $totalPerPage.

Still with me? I hope so, because now we’ll do some math(yaay!…).

1
2
3
4
5
6
7
8
9
10
11
12
		public function setPage($page) {
 
			if(is_numeric($page)) {
 
				$this->currentPage = mysql_real_escape_string($page);
				$this->firstResult = (($this->currentPage * $this->totalPerPage) - $this->totalPerPage);
 
				return $this->firstResult;
 
			}
 
		}

Same here, we use $page as a variable when calling the function. This value will ofcourse be the value of the current page(for example 2 = we’re looking on page 2).
We check if it’s an integer because we’re not allowing anything else to be passed, and if it is, we assign the value of $page, to private $currentPage.

After that, the fun begins… or not, depending if you enjoy math.
Some way, we need to calculate the number of the first result on THAT page. So we need to take into consideration how many results we are allowing per page, and also what the current page is.

1
$this->firstResult = (($this->currentPage * $this->totalPerPage) - $this->totalPerPage);

Let’s just play with the thought that you’re viewing page 3, and you’ve set the configuration so it’s displaying 10 results per page.
Then it would be like: 3 * 10, which is 30. But that’s just the amount of result you’ve viewed after reading whole page 3, and we want the first result, so we need to subtract it by the amount of results you’ve allowed it to display PER PAGE, leaving us with:
(3*10) - 10 = 20

Not really hard, but took some time to figure out.

After that, we return the value of the private $firstResult. If we didn’t, we would need to create another function just to get that value, since the variable is private and you cannot get it in any other way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
		public function getPages($results) {
 
			$this->totalResults = count($results);
			$totalPages = $this->totalResults / $this->totalPerPage;
			$this->totalPages = ceil($totalPages);
 
			$x = 1;
			$array = array();
 
			while($x <= $this->totalPages) {
 
				$array[] = $x;
				$x++;
 
			}
 
			return $array;
 
		}

This function is quite big. The biggest function in this class actually.

The first thing we do here, is to count the amount of results, and assigning that value to private $totalResults.
After that, we calculate how many pages we get out of those results, based on the value of private $totalPerPage.

Again, I’m going to use my previous example.
30 results, and 10 results per page: 30 / 10 = 3 pages. This is basic math.

After that we ceil it, and what that does, is to round it up. Because what if when we divide, it gives us 7,43 pages, we don’t want that, now do we?
So we round that up to 8, and that’s what the ceil function do.

Since private $totalPages is just an integer, and I want it to be an array, I’m creating an array inside this function that will be used only in this function and then returned.

I assign the value of 1 to the variable $x, and I create an array of the variable $array.
Then I use a while loop.

while $x is less or equal to private $totalPages, we do the things inside the bracket. And that is to assign the value of $x to a key inside the array $array, and after that we add 1 value to $x, and this is looped again and again until $x is higher than private $totalPages.

After that we return the array.

1
2
3
4
5
6
7
8
9
10
11
		public function checkLink($pagenr) {
 
			if($pagenr <= $this->totalPages && $pagenr >= 1) {
 
				return true;
 
			}
 
			return false;
 
		}

This is really simple. We just check if the $pagenr is within page 1, and the private $totalPages.
If it is, we return true. If it’s not, we return false.

1
2
3
4
5
6
7
8
9
		public function getCurrentPage() {
 
			$array = array();
			$array[] = $this->currentPage;
			$array[] = $this->totalPages;
 
			return $array;
 
		}

Quite simple too. I’m just assigning the value of private $currentPage and private $totalPages to 2 different keys in an array.
Note that this array is also called $array, but it’s NOT the same as the one in the getPages function.
PHP Tip: If you create a variable inside a function in a class, that variable is only set in THAT function and NEVER outside UNLESS you create that variable as a $this variable in the beginning of the class.

This is basicly the whole class. It’s quite short, I know, but it certainly does the job!
Here’s the whole script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
||||||||||||||||||||||||||||||||||||||||||
|||| @author Tanax
|||| @copyright 2008
||||||||||||||||||||||||||||||||||||||||||
**/
 
	class pagination {
 
		// The total values.
		private $totalPages;
		private $totalResults;
		private $totalPerPage;
 
		// The current values.
		private $currentPage;
 
		// The first result on current page.
		private $firstResult;
 
		/**
		 *	Sets the maximum allowed results per page
		 *
		 *	@param integer $max, default 10
		**/
		public function setMax($max = 10) {
 
			if(is_numeric($max)) {
 
				$this->totalPerPage = $max;
 
			}
 
		}
 
		/**
		 *	Generate the first result on the current page
		 *
		 *	@param integer $page, which page we're currently viewing
		 *	@return integer first result
		**/
		public function setPage($page) {
 
			if(is_numeric($page)) {
 
				$this->currentPage = mysql_real_escape_string($page);
				$this->firstResult = (($this->currentPage * $this->totalPerPage) - $this->totalPerPage);
 
				return $this->firstResult;
 
			}
 
		}
 
		/**
		 *	Generates how many pages based on the total amount of results
		 *
		 *	@param array $results, an array of all the results
		 *	@return array of pages
		**/
		public function getPages($results) {
 
			$this->totalResults = count($results);
			$totalPages = $this->totalResults / $this->totalPerPage;
			$this->totalPages = ceil($totalPages);
 
			$x = 1;
			$array = array();
 
			while($x <= $this->totalPages) {
 
				$array[] = $x;
				$x++;
 
			}
 
			return $array;
 
		}
 
		/**
		 *	Checks if a link is valid
		 *
		 *	@param integer $pagenr, the number of the page you want to check if it exist
		 *	@return true or false
		**/
		public function checkLink($pagenr) {
 
			if($pagenr <= $this->totalPages && $pagenr >= 1) {
 
				return true;
 
			}
 
			return false;
 
		}
 
		/**
		 *	Generate the current page number
		 *
		 *	@return array, [0] = the current page, [1] = total pages
		**/
		public function getCurrentPage() {
 
			$array = array();
			$array[] = $this->currentPage;
			$array[] = $this->totalPages;
 
			return $array;
 
		}
 
	}

Examples:

So, how do you use this class you ask?
Well, here’s 2 examples, 1 by me, and the 2nd one is by Salathe from talkphp.
Read the comments in the scripts for explanation.

MySQL example:

Image Gallery script, non-MySQL:

An example which uses a directory of images is given below. The folder structure is such that we have an images folder and within that a thumbs folder. Filenames match between the folders representing a thumbnail and full-sized version of the same image. It’s up to you to create the thumbnails however you like.

So this is everything. I hope you learned something, and stay tuned for more tutorials!

Tanax on March 18th 2008 in Coding, PHP, Tutorials

2 Responses to “PHP: Pagination Class”

  1. Yas responded on 02 Apr 2008 at 5:02 am #

    Good explanation. Thanks for the tutorial. :)

    One thing, an explanation of the examples would make it perfect. Especially for people who are relatively new to OOP in PHP.

    =)

  2. RRy responded on 15 Apr 2008 at 4:59 pm #

    Hello Tanax,

    I just wanted to take a moment and thank you for posting this. I’ve been searching high and low for a tutorial or script that would list items and create a navigation for them.

    Thank you!

Trackback URI | Comments RSS

Leave a Reply