Completely customisable PHP pagination class
If you need to paginate your database results quickly and reliably then this could be the class for you. It allows you complete access to all attributes of the pagination, from the link templates to the results padding, and auto querying.
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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | /******************************************************************************* * Pagination class * * Created: 12th January 2009 * * Updated: 15th May 2010 * * ©Copyright Jay Gilford 2009 * * http://www.jaygilford.com * * email: jay [at] jaygilford.com * *******************************************************************************/ class pagination { ################################ # PRIVATE VARS - DO NOT ALTER # ################################ private $_query = ''; private $_current_page = 1; private $_padding = 2; private $_results_resource; private $_output; ################################ # RESULTS VARS # ################################ public $results_per_page = 10; #Number of results to display at a time public $total_results = 0; #Total number of records public $total_pages = 0; #Total number of pages public $link_prefix = '/?page='; #String for link to go before the page number public $link_suffix = ''; #String for link to go after the page number public $page_nums_separator = ' | '; #String to go between the page number links ################################ # ERROR HOLDING VAR # ################################ public $error = null; ################################ # PAGINATION TEMPLATE DEFAULTS # ################################ public $tpl_first = '<a href="{link}">«</a> | '; public $tpl_last = ' | <a href="{link}">»</a> '; public $tpl_prev = '<a href="{link}">‹</a> | '; public $tpl_next = ' | <a href="{link}">›</a> '; public $tpl_page_nums = '<span><a href="{link}">{page}</a></span>'; public $tpl_cur_page_num = '<span>{page}</span>'; /** * In the above templates {link} is where the link will be inserted and {page} is * where the page numbers will be inserted. Other than that, you can modify them * as you please * * NOTE: You should have a separator of some sort at the right of $tpl_first and * $tpl_prev as above in the defaults, and also have a separator of some sort * before the $tpl_next and $tpl_last templates **/ ################################################################################## public function __construct($page, $query) { #Check page number is a positive integer greater than 0 and assign it to $this->_current_page if ((int)$page > 0) $this->_current_page = (int)$page; #Remove any LIMIT clauses in the query string and set if $query = trim(preg_replace('/[\s]+LIMIT[\s]+\d+([\s,]*,[^\d]*\d+)?/i', '', $query)); if (empty($query)) { return false; } else { $this->_query = $query; } } /** * pagination::paginate() * * Processes all values and query strings and if successful * returns a string of html text for use with pagination bar * * @return string; */ public function paginate() { $output = ''; ######################################### # GET TOTAL NUMBER OF RESULTS AND PAGES # ######################################### $result = mysql_query($this->_query); if (!$result) { $this->error = __line__ . ' - ' . mysql_error(); return false; } $this->total_results = mysql_num_rows($result); $this->total_pages = ceil($this->total_results / $this->results_per_page); ######################## # FREE RESULT RESOURCE # ######################## ################################ # IF TOTAL PAGES <= 1 RETURN 1 # ################################ if ($this->total_pages <= 1) { $this->_results_resource = $result; $this->_output = '1'; return $this->_output; } mysql_free_result($result); ################################################### # CHECK CURRENT PAGE ISN'T GREATER THAN MAX PAGES # ################################################### if ($this->_current_page > $this->total_pages) $this->_current_page = $this->total_pages; ###################################### # SET FIRST AND LAST PAGE VALUES AND # # ERROR CHECK AGAINST INVALID VALUES # ###################################### $start = ($this->_current_page - $this->_padding > 0) ? $this->_current_page - $this-> _padding : '1'; $finish = ($this->_current_page + $this->_padding <= $this->total_pages) ? $this-> _current_page + $this->_padding : $this->total_pages; ########################################### # CREATE LIMIT CLAUSE AND ASSIGN TO QUERY # ########################################### $limit = ' LIMIT ' . ($this->results_per_page * ($this->_current_page - 1)) . ',' . $this->results_per_page; $query = $this->_query . $limit; ############################################# # RUN QUERY AND ASSIGN TO $_result_resource # ############################################# $result = mysql_query($query); if ($result === false) { $this->error = __line__ . ' - ' . mysql_error(); return false; } $this->_results_resource = $result; ########################################### # ADD FIRST TO OUTPUT IF CURRENT PAGE > 1 # ########################################### if ($this->_current_page > 1) { $output .= preg_replace('/\{link\}/i', $this->link_prefix . '1' . $this-> link_suffix, $this->tpl_first); } ########################################## # ADD PREV TO OUTPUT IF CURRENT PAGE > 1 # ########################################## if ($this->_current_page > 1) { $output .= preg_replace('/\{link\}/i', $this->link_prefix . ($this-> _current_page - 1) . $this->link_suffix, $this->tpl_prev); } ################################################ # GET LIST OF LINKED NUMBERS AND ADD TO OUTPUT # ################################################ $nums = array(); for ($i = $start; $i <= $finish; $i++) { if ($i == $this->_current_page) { $nums[] = preg_replace('/\{page\}/i', $i, $this->tpl_cur_page_num); } else { $patterns = array('/\{link\}/i', '/\{page\}/i'); $replaces = array($this->link_prefix . $i . $this->link_suffix, $i); $nums[] = preg_replace($patterns, $replaces, $this->tpl_page_nums); } } $output .= implode($this->page_nums_separator, $nums); ################################################## # ADD NEXT TO OUTPUT IF CURRENT PAGE < MAX PAGES # ################################################## if ($this->_current_page < $this->total_pages) { $output .= preg_replace('/\{link\}/i', $this->link_prefix . ($this-> _current_page + 1) . $this->link_suffix, $this->tpl_next); } ############################################ # ADD LAST TO OUTPUT IF FINISH < MAX PAGES # ############################################ if ($this->_current_page < $finish) { $output .= preg_replace('/\{link\}/i', $this->link_prefix . $this->total_pages . $this->link_suffix, $this-> tpl_last); } $this->_output = $output; return $output; } /** * pagination::padding() * * Sets the padding for the pagination string * * @param int $val * @return bool */ public function padding($val) { if ((int)$val < 1) return false; $this->_padding = (int)$val; return true; } /** * pagination::resource() * * Returns the resource of the results query * * @return resource */ function resource() { return $this->_results_resource; } /** * pagination::__tostring() * returns the last pagination output * * @return string */ function __tostring() { if (trim($this->_output)) { return trim($this->_output); }else{ return ''; } } } |
Instructions on class usage:
To create an instance of the class, call it with your current page and the query you want to run
$paginator = new pagination($page_num_variable, 'SELECT * FROM `table_name`');
After that, you need to set up any of the parameters for the class such as
$paginator->results_per_page = 15;
$paginator->padding(5);
$paginator->link_prefix = '/results/page/';
$paginator->link_suffix = '/';
$paginator->page_nums_separator = ' -=- ';
Once you have done that, you can call the paginate method
NOTE: you must be connected to your database in order to run this method as it uses the mysql_query function.
The paginate method returns the string of html for you to insert and sets the $pagination->resource() to be the resource id of the query that is run for the pagination
You can use either the returned paginate() string or echo the variable name of the class and it will generate the pagination
So either$page_links = $paginator->paginate();
And then
echo $page_links; wherever you want the links to go.
Alternatively you can use
$paginator->paginate();
and then
echo $paginator;
When you are using mysql_fetch_array() or mysql_fetch_assoc to get your data from your database, you simply need to replace your old resource handle with $paginator->resource();
Example:
1 2 3 4 | while($row = mysql_fetch_assoc($paginator->resource())) { echo $row['field_name']; } |
If you have any questions, bugs or suggestions regarding this class, feel free to contact me either by comment or via one of the contact methods in the contact section
Jay
Tags: advanced, class, MySQL, object, paginate, pagination, PHP

February 2nd, 2010 at 8:09 am
$paginator->link_prefix = ‘/results/page/’;
i get forbidden error, the url miss the link in it…
parameter is not working, works only when its set inside the pagination.class.php
February 2nd, 2010 at 1:02 pm
Did you create an object called $paginator? It sounds like you’ve mis-typed something, or perhaps you’ve got the class out of scope, but with no actual source code i cannot help
February 3rd, 2010 at 12:33 pm
thank you it worked my link was broken?
July 3rd, 2010 at 11:25 am
Really good class Jay. Will be using parts of that :)
Only thing I’d point out is the part where you’re obtaing a total row count from the database (line 100 in your code above).
This way is fine if you absolutely need to an exact count of the number of rows, but on larger sites will hammer you database. My personal preference would be to cache the row and then store a total row count in a session variable. E.g.
$this->total_results = ( isset($_SESSION['rowCount']) ) ? intval($_SESSION['rowCount']) : mysql_num_rows($result);
Again, if you absolutely need an exact accurate count you’ll need to query the db each time, but I’ve found for the majority of the time a cached result is fine.
Rob
}
July 13th, 2010 at 3:52 am
Hi Rob,
Yes you are right, it’s not the most efficient of ways of getting the total number
That said, if you have query caching enabled on your mysql server you shouldn’t actually notice a great deal of difference, since mysql will cache the result sets