Limit Pagination Page Number

Limit pagination page number

Ok if you mean show something like

Prev 1 2 3 4 5 6 .. 40 41 Next 
Prev 1 2 .. 6 7 8 9 10 .. 40 41 Next

First thing we need to is create a function that can process what we need to output the pagination. Heres a function I use and it works well.

function get_paging_info($tot_rows,$pp,$curr_page)
{
$pages = ceil($tot_rows / $pp); // calc pages

$data = array(); // start out array
$data['si'] = ($curr_page * $pp) - $pp; // what row to start at
$data['pages'] = $pages; // add the pages
$data['curr_page'] = $curr_page; // Whats the current page

return $data; //return the paging data

}

Now this function is pretty solid and works very well for me.

So you pass this function

  • $tot_rows = counted rows for query
  • $pp = items per page
  • $curr_page = the current page number

Ok, now that you have the data you need, you'll need to display it.

Heres what I use and please read it before you think, 'ah, it's too long'. It's actually very simple.

Heres a snapshot of what it will return

Sample Image

    <!-- Create the query -->
<?php $count = mysql_fetch_assoc( mysql_query ( "SELECT COUNT( rows ) as count FROM table" ) ) ;

<?php $count = $count[0]['count']; ?>

<!-- Call our function from above -->
<?php $paging_info = get_paging_info($count,5,34); ?>

<p>
<!-- If the current page is more than 1, show the First and Previous links -->
<?php if($paging_info['curr_page'] > 1) : ?>
<a href='' title='Page 1'>First</a>
<a href='' title='Page <?php echo ($paging_info['curr_page'] - 1); ?>'>Prev</a>
<?php endif; ?>

<?php
//setup starting point

//$max is equal to number of links shown
$max = 7;
if($paging_info['curr_page'] < $max)
$sp = 1;
elseif($paging_info['curr_page'] >= ($paging_info['pages'] - floor($max / 2)) )
$sp = $paging_info['pages'] - $max + 1;
elseif($paging_info['curr_page'] >= $max)
$sp = $paging_info['curr_page'] - floor($max/2);
?>

<!-- If the current page >= $max then show link to 1st page -->
<?php if($paging_info['curr_page'] >= $max) : ?>

<a href='' title='Page 1'>1</a>
..

<?php endif; ?>

<!-- Loop though max number of pages shown and show links either side equal to $max / 2 -->
<?php for($i = $sp; $i <= ($sp + $max -1);$i++) : ?>

<?php
if($i > $paging_info['pages'])
continue;
?>

<?php if($paging_info['curr_page'] == $i) : ?>

<span class='bold'><?php echo $i; ?></span>

<?php else : ?>

<a href='' title='Page <?php echo $i; ?>'><?php echo $i; ?></a>

<?php endif; ?>

<?php endfor; ?>

<!-- If the current page is less than say the last page minus $max pages divided by 2-->
<?php if($paging_info['curr_page'] < ($paging_info['pages'] - floor($max / 2))) : ?>

..
<a href='' title='Page <?php echo $paging_info['pages']; ?>'><?php echo $paging_info['pages']; ?></a>

<?php endif; ?>

<!-- Show last two pages if we're not near them -->
<?php if($paging_info['curr_page'] < $paging_info['pages']) : ?>

<a href='<?php echo str_replace('/page'.$paging_info['curr_page'], '', $paging_info['curr_url']) . '/page'.($paging_info['curr_page'] + 1); ?>' title='Page <?php echo ($paging_info['curr_page'] + 1); ?>'>Next</a>

<a href='<?php echo str_replace('/page'.$paging_info['curr_page'], '', $paging_info['curr_url']) . '/page'.$paging_info['pages']; ?>' title='Page <?php echo $paging_info['pages']; ?>'>Last</a>

<?php endif; ?>
</p>

Pagination - Limit the visible page numbers

I think you got a bit confused with a couple of bits. Try this - I've edited the code in your updated post. Before you edit the code to tweak things, see what result you get with what I've posted here.

I've replaced $_GET['start'] with $_GET['page']. $_GET['page'] is now the page number and not the start row.

DATABASE:

<?php

try {

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

/*
Set default page value to 1
*/

$current_page = 1;

/*
If $_GET['start'] exists, is a valid integer and is positive set $current_page to this value
*/

if (isset($_GET['page']) && is_int($_GET['page']) && $_GET['page'] >= 0) {
$current_page = $_GET['page'];
}

/*
Set $max_rows to the number of records you want to show on each page
*/

$max_rows = 10;

/*
Set default values for pagination variables - don't change this
*/
$total_rows = 0;
$total_pages = 1;
$prev_page = 0;
$next_page = 0;
$page_from = 1;
$page_to = 0;

/*
Your original row count query
*/

$count_query = "SELECT product_name, product_quantity, product_id, product_price_lowest, product_price_highest FROM product";
$stmt = $conn->prepare($count_query);
$stmt->execute();

$total_rows = $stmt->rowCount();

/*
Set $total_pages to ceiling of row count / max rows
*/

$total_pages = ceil($total_rows / $max_rows);

/*
If $current_page is higher than total pages, reset to $total_pages
*/
if ($current_page > $total_pages) $current_page = $total_pages;

/*
Set start row for DB query
*/
$db_start_row = ($current_page * $max_rows) - $max_rows;

// query to get messages from messages table
$connOne = "SELECT product_name, product_quantity, product_id, product_price_lowest, product_price_highest FROM product ORDER BY product_price_lowest ASC, product_price_highest DESC LIMIT $db_start_row, $max_rows";
$stmt = $conn->prepare($connOne);
$stmt->execute();

if($stmt->rowCount() > 0){
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
}

/*
Set variables to control which page numbers are shown
*/

$page_to = $total_pages;
if ($current_page > 1) $prev_page = $current_page - 1;
if ($total_pages > $current_page) $next_page = $current_page + 1;
if ($total_pages > 5) {
if (($current_page - 2) > 1) $page_from = $current_page - 2;
if (($current_page + 2) < $total_pages) $page_to = $current_page + 2;
}
}

catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}

$conn = null;
?>

PAGE OUTPUT:

<?php

/*
* Check that we've actually got some records, although
* I assume you're doing this elsewhere
*/
if ( $total_rows > 0 ) {

echo '<ul>';

/*
* If we're not on the first page show a link to page 1 and an ellipsis
*/
if ( $prev_page > 0 ) {
echo '<li><a href="?page=' . $prev_page . '">Previous</a></li>';
}
if ( $page_from != 1 ) {
echo '<li><a href="?page=1">1</a></li>';
echo '<li><span>...</span></li>';
}

/*
* Loop through the page numbers that we're showing and set class="active"
* on the current page
*/
for ( $p = $page_from; $p <= $page_to; $p++ ) {
echo '<li' . ( $current_page == $p ? ' class="active"' : '' ) . '><a href=?page=' . $p . '>' . $p . '</a></li>';
}

/*
* If we're not on the last page show an ellipsis and a link to the last page
*/
if ( $page_to != $total_pages ) {
echo '<li><span>...</span></li>';
echo '<li><a href="?page=' . $total_pages . '">' . $total_pages . '</a></li>';
}
if ( $next_page > 0 ) {
echo '<li><a href="?page=' . $next_page . '">Next</a></li>';
}

echo '</ul>';

} else {
echo 'No records.';
}

?>

Limit number of pages in pagination

Post current page number to the PHP script and apply the following logic:

$startPage = 1;
$endPage = $page+ 3;
if($currentPageNo > 3){
$startPage = $page - 3;
}

for ($i=$startPage; $i<=$endPage; $i++) {
if ($i == $page) {
$pagLink .= "<a class='active' href='#'>".$i."</a>";
} else {
$pagLink .= " <a href='news.php?page=".$i."'>".$i."</a>";
}
};

php pagination - how do i limit the number of pages show

You need to change your for-cycle, the starting point and ending point

$count = 9;
$startPage = max(1, $page - $count);
$endPage = min( $pages, $page + $count);
for($i = $startPage; $i < $endPage; $i++) {
// write out the link to the page
}

then if the page is 250 it will show only 241, 242, ..., 250, ..., 257, 258

Limit Pagination Numbers

The first part of your question is easy

However I would like it to only display 5 page numbers

for (var s=0; s<Math.min(totalPages,5); s++) {
nav += '<li class="numeros"><a href="#">'+ (s + 1) + '</a></li>';
}

This limits the number of page numbers displayed to totalPages or 5 whichever is smaller.
For the second part of your question - seeing as you found a lugin which does exactly what you want there's not much point trying to replicate the behaviour. You're better off just using it directly. The appropriate code would be along the lines of:

pageSize = 2;
pagesCount = $(".content").length;
var totalPages = Math.ceil(pagesCount / pageSize)

$('.pagination').twbsPagination({
totalPages: totalPages,
visiblePages: 5,
onPageClick: function(event, page) {
var startIndex = (pageSize * (page - 1))
var endIndex = startIndex + pageSize
$('.content').hide().filter(function() {
var idx = $(this).index();
return idx >= startIndex && idx < endIndex;
}).show()
}
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twbs-pagination/1.4.1/jquery.twbsPagination.js"></script>

<div class="contents text-center">
<div class="content">
<h1>NEWS 1</h1>
<h3>Page 1 contents...</h3>
</div>
<div class="content">
<h1>NEWS 2</h1>
<h3>Page 2 contents...</h3>
</div>
<div class="content">
<h1>NEWS 3</h1>
<h3>Page 3 contents...</h3>
</div>
<div class="content">
<h1>NEWS 4</h1>
<h3>Page 4 contents...</h3>
</div>
<div class="content">
<h1>NEWS 5</h1>
<h3>Page 5 contents...</h3>
</div>
<div class="content">
<h1>NEWS 6</h1>
<h3>Page 6 contents...</h3>
</div>
<div class="content">
<h1>NEWS 7</h1>
<h3>Page 7 contents...</h3>
</div>
<div class="content">
<h1>NEWS 8</h1>
<h3>Page 8 contents...</h3>
</div>
<div class="content">
<h1>NEWS 9</h1>
<h3>Page 9 contents...</h3>
</div>
<div class="content">
<h1>NEWS 10</h1>
<h3>Page 10 contents...</h3>
</div>
<div class="content">
<h1>NEWS 11</h1>
<h3>Page 11 contents...</h3>
</div>
</div>

<nav class="text-center">
<ul class="pagination">
</ul>
</nav>

Limit the number of visible pages in pagination

I would suggest using a function that -- given a current page number, the total number of pages, and the maximum number of buttons you want to have -- will return an array of numbers, where 0 denotes a ... button, and other numbers denote clickable page buttons.

So for example, it could return:

[1, 2, 0, 5, 6, 7, 0, 10, 11]

...which would represent the following buttons:

1, 2, ..., 5, 6, 7, ..., 10, 11

That function will do the hard work of calculating where those ... should be placed, but once you have that, it is a piece of cake to integrate it with your page.

Here is an example that will limit the number of buttons (excluding prev/next, including ... buttons) to 7. You can reduce that parameter to 5 if you like:

// Returns an array of maxLength (or less) page numbers// where a 0 in the returned array denotes a gap in the series.// Parameters://   totalPages:     total number of pages//   page:           current page//   maxLength:      maximum size of returned arrayfunction getPageList(totalPages, page, maxLength) {    if (maxLength < 5) throw "maxLength must be at least 5";
function range(start, end) { return Array.from(Array(end - start + 1), (_, i) => i + start); }
var sideWidth = maxLength < 9 ? 1 : 2; var leftWidth = (maxLength - sideWidth*2 - 3) >> 1; var rightWidth = (maxLength - sideWidth*2 - 2) >> 1; if (totalPages <= maxLength) { // no breaks in list return range(1, totalPages); } if (page <= maxLength - sideWidth - 1 - rightWidth) { // no break on left of page return range(1, maxLength - sideWidth - 1) .concat(0, range(totalPages - sideWidth + 1, totalPages)); } if (page >= totalPages - sideWidth - 1 - rightWidth) { // no break on right of page return range(1, sideWidth) .concat(0, range(totalPages - sideWidth - 1 - rightWidth - leftWidth, totalPages)); } // Breaks on both sides return range(1, sideWidth) .concat(0, range(page - leftWidth, page + rightWidth), 0, range(totalPages - sideWidth + 1, totalPages));}
// Below is an example use of the above function.$(function () { // Number of items and limits the number of items per page var numberOfItems = $("#jar .content").length; var limitPerPage = 2; // Total pages rounded upwards var totalPages = Math.ceil(numberOfItems / limitPerPage); // Number of buttons at the top, not counting prev/next, // but including the dotted buttons. // Must be at least 5: var paginationSize = 7; var currentPage;
function showPage(whichPage) { if (whichPage < 1 || whichPage > totalPages) return false; currentPage = whichPage; $("#jar .content").hide() .slice((currentPage-1) * limitPerPage, currentPage * limitPerPage).show(); // Replace the navigation items (not prev/next): $(".pagination li").slice(1, -1).remove(); getPageList(totalPages, currentPage, paginationSize).forEach( item => { $("<li>").addClass("page-item") .addClass(item ? "current-page" : "disabled") .toggleClass("active", item === currentPage).append( $("<a>").addClass("page-link").attr({ href: "javascript:void(0)"}).text(item || "...") ).insertBefore("#next-page"); }); // Disable prev/next when at first/last page: $("#previous-page").toggleClass("disabled", currentPage === 1); $("#next-page").toggleClass("disabled", currentPage === totalPages); return true; }
// Include the prev/next buttons: $(".pagination").append( $("<li>").addClass("page-item").attr({ id: "previous-page" }).append( $("<a>").addClass("page-link").attr({ href: "javascript:void(0)"}).text("Prev") ), $("<li>").addClass("page-item").attr({ id: "next-page" }).append( $("<a>").addClass("page-link").attr({ href: "javascript:void(0)"}).text("Next") ) ); // Show the page links $("#jar").show(); showPage(1);
// Use event delegation, as these items are recreated later $(document).on("click", ".pagination li.current-page:not(.active)", function () { return showPage(+$(this).text()); }); $("#next-page").on("click", function () { return showPage(currentPage+1); });
$("#previous-page").on("click", function () { return showPage(currentPage-1); });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<div class="pagination"></div>
<div id="jar" style="display:none"> <div class="content">1) Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div> <div class="content">2) Maecenas vitae elit arcu.</div> <div class="content">3) Pellentesque sagittis risus ac ante ultricies, ac convallis urna elementum.</div> <div class="content">4) Vivamus sodales aliquam massa quis lobortis. </div> <div class="content">5) Phasellus id sem sollicitudin lacus condimentum malesuada vel tincidunt neque.</div> <div class="content">6) Donec magna leo, rhoncus quis nunc eu, malesuada consectetur orci.</div> <div class="content">7) Praesent sollicitudin, quam a ullamcorper pharetra, urna lacus mollis sem, quis semper augue massa ac est.</div> <div class="content">8) Etiam leo magna, fermentum quis quam non, aliquam tincidunt erat.</div> <div class="content">9) Morbi pellentesque nibh nec nibh posuere, vel tempor magna dignissim.</div> <div class="content">10) In maximus fermentum elementum. Vestibulum ac lectus pretium, suscipit ante nec, bibendum erat.</div> <div class="content">11) Phasellus sit amet orci at lectus fermentum congue. Etiam faucibus scelerisque purus.</div> <div class="content">12) Pellentesque laoreet ipsum ac laoreet consectetur. </div> <div class="content">13) Integer aliquet odio magna, lobortis mattis tortor suscipit sed.</div> <div class="content">14) Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </div> <div class="content">15) Mauris a tellus luctus turpis elementum imperdiet vitae malesuada mauris. </div> <div class="content">16) Donec id libero sagittis, laoreet lorem vel, tempus nunc. </div> <div class="content">17) Donec vitae neque sed ex tristique hendrerit.</div> <div class="content">18) Aliquam sollicitudin gravida varius.</div> <div class="content">19) Donec auctor, augue sed finibus fermentum, neque erat interdum libero, eget porta metus lectus quis odio.</div> <div class="content">20) Nunc quis ante enim. Etiam nisl orci, hendrerit ut pretium nec, tempor in metus.</div> <div class="content">21) Donec et semper arcu.</div> <div class="content">22) Donec lobortis interdum purus, eu semper nisl pulvinar ac.</div> <div class="content">23) Cras laoreet eu elit vel porta.</div> <div class="content">24) Quisque pharetra arcu eget diam posuere commodo.</div> <div class="content">25) Nulla ornare eleifend neque, eget tincidunt nunc ullamcorper id. Nulla facilisi.</div></div>

How can I limit the page numbers shown in the pagination?

pagination page number limit problem solve by chnage

for ($x=1; $x<=$pages; $x++)

to

for($x = max(1, $page - 5); $x <= min($page + 5, $pages); $x++)


Related Topics



Leave a reply



Submit