To cheerio:
Here's an idea for improvement. When there are lots of pages maybe replacing some of them with "..." so, if there are for example 50 pages and you're on page 30 it may look something like this.
<< 1 2 ... 28 29 30 31 32 ... 49 50 >>
To xfezz:
Cheerios functions doesn't handle limiting the resultset only the displaying of the pagination so this will have to be implemented separately. There are two ways of doing this.
Firstly, you can pull out the entire resultset into a php array and then chop it. Although this isn't the most elegant solution in some situations it may be preferable. Alternatively you can run two queries, one to find the number of rows which would be returned in the entire result set and then another (with a specially crafted LIMIT clause) to grab the required results. I will be showing you how to implement the latter.
Let's start with a case study, a news site, and we want to have a paginated page which shows all news articles in reverse date order. Also, a few assumptions; we have already connected to the database and the connection is in a variable called $con
<?php
// Define a constant to denote how many articles we should show per page
define( 'PAGE_LIMIT', 20 );
// Default to page 1
if(isset($_GET['page']) && ctype_digit( $_GET['page'] )) {
$page = $_GET['page'];
} else {
$page = 1;
}
// First we need to get the total number of articles
// we don't need the ORDER BY clause here so we leave
// it off for the sake of speed
$sql = "SELECT COUNT(*) FROM articles";
$res = mysql_query( $sql, $con )
or trigger_error( "Failed to run query [" . $sql . "]", E_USER_ERROR );
$row = mysql_fetch_row( $res );
$article_count = $row[0];
// Now we can call cheerio's function to generate the page links
$page_links = genPagination( $article_count, $page, 'www.example.org/articles.php?page=', PAGE_LIMIT );
// Now get our actual result set
$sql = "SELECT id, title, date, summary FROM articles ORDER BY date DESC LIMIT " . (PAGE_LIMIT*$page) .", " . PAGE_LIMIT;
$res = mysql_query( $sql, $con )
or trigger_error( "Failed to run query [" . $sql . "]", E_USER_ERROR );
?>
<h1>All Articles (newest first)</h1>
<div class="pagelinks"><?php echo $page_links;?></div>
<?php
while( $row = mysql_fetch_assoc( $res ) ) {
?>
<h2><a href="www.example.org/article/<?php echo($row['id']);?>"><?php echo($row['title']);?></a></h2>
<p><?php echo($row['summary']);?></p>
<?php
}
?>
<div class="pagelinks"><?php echo $page_links;?></div>