Limiting pagination links

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
implications
Forum Commoner
Posts: 25
Joined: Thu Apr 07, 2011 3:59 am

Limiting pagination links

Post by implications »

I've currently set up a pagination but I can't seem to figure out how I can limit the links shown because an overload of data crowds the pagination navigation. If there's over 30 pages, the pagination navigation looks way too cluttered. How can I adjust my current code so after 5 pages there's an ellipsis (...) and the link to the very last page after the ellipsis. Kind of like the way this forum's pagination is set up.

Code: Select all

if(!isset($_GET['page'])) {
	$page = 1;
} else {
	$page = (int)$_GET['page'];
}
$from = (($page * $total_questions) - $total_questions);

$result = mysql_query("SELECT * FROM $db_table WHERE answer != '' ORDER BY dateasked DESC LIMIT $from, $total_questions");
$count_unanswered = mysql_query("SELECT * FROM Ask WHERE answer!=''");
$unanswered = mysql_num_rows($count_unanswered);

if ($unanswered > 0) {

while($row = mysql_fetch_array($result)) {
	$getdate = $row['dateasked'];
	$getquestion = $row['question'];
	$getanswer = $row['answer'];
	echo "<div class='question'>";
  	echo "<b>Q: $getquestion</b><br>";
  	echo "A: $getanswer";
	echo "</div>";
  }

$total_results = mysql_fetch_array(mysql_query("SELECT COUNT(*) as num FROM $db_table WHERE answer != ''"));
$total_pages = ceil($total_results['num'] / $total_questions);
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Limiting pagination links

Post by Celauran »

You know how many total pages there are, and you know the current page being displayed. Let's say you want links to five pages. If $current_page + 2 < 5, display the first five pages. If $current_page + 2 > $total_pages, display the last five pages. Otherwise, display $current_page - 2 through $current_page + 2. Or something to that effect.
Post Reply