Really simple PHP pagination
By Synook in Tutorials, PHP on Saturday August 16th, 2008 | 2 comments | No diggs
Recently, the post count became so high for this blog that I had to implement pagination for them. Pagination can be quite troublesome sometimes, but eventually I came up with a really simple solution.
For the page, we simply use the querystring. In this example, let us use $_GET['page'] to initiallize the $page variable. If the GET var isn't set we default to page 1.
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
Now, we want to figure out how many pages are in our query. For this, we can use the COUNT() SQL function, then divide the number returned by the amount of results per page we want.
$pages = implode(mysql_fetch_assoc(mysql_query("SELECT COUNT(key) FROM table")));
$pages = ceil($pages / 6);
Now, because we may have other GET variables set we want to preserve the querystring. To do this, we just assemble all the current variables (except the page one, of course) into a string.
$querystring = "";
foreach ($_GET as $key => $value) {
if ($key != "page") $querystring .= "$key=$value&";
}
Then, we can loop through the pages, and echo out the links to them. Using a conditional or ternary operator we can also assign a different class to the current page.
echo "Pages: ";
for ($i = 1; $i <= $pages; $i++) {
echo "<a " . ($i == $page ? "class=\"selected\" " : "");
echo "href=\"?{$querystring}page=$i";
echo "\">$i</a> ";
}
Then, to display only the results that are relevant to the current page we can use the LIMIT SQL clause, or in this case LIMIT $page, 6 (because we have 6 results per page).
$result = mysql_query("SELECT * FROM table LIMIT $page, 6);
2 comments
- I believe it would be far more efficient to just cast two queries at the same time. One with LIMIT, and one with SELECT FOUND_ROWS() like so:
"SELECT SQL_CALC_FOUND_ROWS * FROM table LIMIT $page, 6;
SELECT FOUND_ROWS();"
Then again, after reading the PHP documentation on MySQL, it seems mysql_query() doesn't support multiple queries. Have you considered upgrading to MySQLi? I know for sure it has a multy query aware function.
Comment by boen_robot - Hi boen_robot,
I haven't looked much at mysqli, but you are right, there should be an efficiency gain if FOUND_ROWS was used instead of a seperate COUNT query.
Comment by Synook
RoundedDesign Blog
Categories
- (X)HTML & CSS (10)
- JavaScript (5)
- News (3)
- Other (3)
- PHP (8)
- The Lab (8)
- Tutorials (10)
