Truncate number of pages in pagination - php

This might be a quite silly question, but I can't figure anything out that might help me go further. I'm looking to shorten the number of NUMBERS in my page navigation.
Instead of being like: 1, 2, 3, 4, 5, 6, 7, 8
I want it be like: 1, 2...7, 8
And when I go to 2, number 3 should now be seen in the numbers group.
Here is my code that is in charge of the page numbers:
<div id="user_nav_bottom">
<?php for($i=1; $i < sizeof($pages)+1; $i++) {
$strong = ($_GET['page'] == $i) ? ' dark bold' : '';
echo '<span class="normal' . $strong . '">' . $i . ', </span>';
} ?>
</div>

This is a modified chunk of code I wrote for paging forums.
It's output isn't exactly how you showed but should just be a matter of tweaking.
<?php
//Set up vars
$currentPage = isset($_GET["page"])? $_GET["page"] : 1;
$numPages = count($pages);
$numPages = 7;//cause I don't have the real var for testing
$howMany = 1;
?>
<?php if ($numPages > 1): ?>
<li>Page <?php echo $currentPage?> of <?php echo $numPages?></li>
<?php if ($currentPage > 1): ?>
<li>First</li>
<li><</li>
<?php endif; ?>
<?php if ($currentPage > $howMany + 1): ?>
<li>...</li>
<?php endif; ?>
<?php for ($pageIndex = $currentPage - $howMany; $pageIndex <= $currentPage + $howMany; $pageIndex++): ?>
<?php if ($pageIndex >= 1 && $pageIndex <= $numPages): ?>
<li>
<?php if ($pageIndex == $currentPage): ?>
<u>
<?php endif; ?>
<?php echo $pageIndex?>
<?php if ($pageIndex == $currentPage): ?>
</u>
<?php endif; ?>
</li>
<?php endif; ?>
<?php endfor; ?>
<?php if ($currentPage < $numPages - $howMany): ?>
<li>...</li>
<?php endif; ?>
<?php if ($currentPage < $numPages): ?>
<li>></li>
<li>Last</li>
<?php endif; ?>
<?php endif; ?>

Check this out: https://codereview.stackexchange.com/a/10292. This solution should solve your problem. I think its a very good approach.

This one shows two links before and two after the current requested link:
<div id="user_nav_bottom">
<?php
$current = $_GET['page'];
$last = count($pages)+1;
$curr0 = $current-2;
$curr1 = $current+2;
if ($curr0<=1) {
$curr0 = 1;
$curr1 = $last>5? 5 : $last;
}
if ($curr1>=$last) {
$curr0 = $last-4 < 1 ? 1 : $last-4;
$curr1 = $last;
}
// now print all links:
echo '« ';
for ($i=$curr0; $i<=$curr1; $i++) {
$style = ($i==$current)? 'font-weight:bold':'';
echo ' '.$i.' ';
}
echo '» ';
?>
</div>
This shows links like this: « 13 14 15 16 17 »
Imho it's not so difficult to add also first five and last five links by adding appropriate conditions.
Testing script here

What you might want to do is use the "logarithmic" pagination technique described in my answer here:
How to do page navigation for many, many pages? Logarithmic page navigation
If you set LINKS_PER_STEP to a low value like 2 or 3, it'll produce very compact output.

Related

How to create pagination that shows previous and next 3 pages

I want to show a pagination which only shows the recent and next 3 pages, but I can't get it working.
Here's my current code:
$stmt = MySQL::connection3()->prepare("SELECT COUNT(ID) AS TOTAL FROM products");
$stmt->execute();
$row = $stmt->fetch();
$total_pages = ceil(intval($row["TOTAL"]) / $results_per_page);
foreach (range(1, $total_pages) as $i) {
if ($i == $page) {
?>
<li class="page-item active">
<?php echo $i ?>
</li>
<?php
} else {
?>
<li class="page-item">
<?php echo $i ?>
</li>
<?php
}
}
Thanks!
I create this example you can run and adapt with your code:
<style>.active{color:green!important}</style>
<?php
echo get_pagination_links('10','100');
function get_pagination_links($current_page, $total_pages)
{
$links = "";
if ($total_pages >= 1 && $current_page <= $total_pages) {
$i = max(2, $current_page - 3);
for (; $i < min($current_page + 4, $total_pages); $i++) {
if($i==$current_page){
$links .= "<li class='page-item active'><a href='?page=$i;' class='page-link'>$i</a></li>";
}else{
$links .= "<li class='page-item'><a href='?page=$i;' class='page-link'>$i</a></li>";
}
}
return $links;
}
}
?>
Output:
7-8-9-10-11-12-13
obviously I didn't connect a database and therefore I used a static result

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

I am having difficulties understanding how to limit the number of pages with pagination. I am trying to list my articles in my DB but I have over 500 pages! I would only like to show a max of about 15 page numbers at a time. I can't seem to understand the answers given in the other questions.
Here is my code for the Pagination:
<?php
require 'core/init.php';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if(!isset($_GET['page'])){
$_GET['page'] = 1;
}
if(! (int)$_GET['page']){
$_GET['page'] = 1;
}
if($_GET['page'] < 1){
$_GET['page'] = 1;
}
$perPage = 18;
$start = ($page > 1) ? ($page * $perPage) - $perPage : 0;
$articles = DB::getInstance()->query("SELECT SQL_CALC_FOUND_ROWS * FROM articles ORDER BY added DESC LIMIT {$start}, {$perPage}");
foreach($articles->results() as $article){ ?>
<div class="article-container">
<h2><?php echo $article->title; ?></h2>
</div>
<?php
}
// pagination
$total = DB::getInstance()->query("SELECT FOUND_ROWS() as total");
$total = $total->results()[0];
foreach ($total as $total => $value) {
}
$pages = ceil($value / $perPage);
$maxpage = 15;
?>
<div class="pagination">
<?php if($_GET['page'] >= 2){
echo 'Prev';
}
for ($i=1; $i <= $pages; $i++) : ?>
<a href="?page=<?php echo $i; ?>" <?php if($page === $i) { echo 'class="pageSelected"'; } ?>><?php echo $i; ?></a>
<?php endfor;
if((int)$_GET['page'] != $i - 1 ){
echo 'Next';
}
?>
</div>
This works as expected but it only spits out the number of pages from 1 to 500. What is the best/easiest way to show something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 ... >
?
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

How to limit the number of pagination pages - PHP

I have this algorithm I made for pagination.
The $array variable is a result set from the query after the page number and limit has been set. It's a result from a PDO::fetchAll() function.
The $array["totalCount"] contains the count of ALL the rows in the table, not only that set but all the rows.
What I want is to limit the number of pages displayed, and make it somehow like google style pagination, I've search a lot of similar questions online, but what makes me struggle is to guess how I can implement it in my algorithm which is much different from others.
Thanks in advance.
public static function renderPaginationBar($obj, $params) {
$array = $obj->getAll($params);
$set = $params["set"];
$perSet = $params["limit"];
$pages = ceil((int)$array["totalCount"] / (int)$perSet);
if($pages > 1 && $set <= $pages) {
$query = preg_replace('/set=\d*/i', '', http_build_query($_GET));
?>
<ul class="pagination">
<?php
if($set > 1) {
?>
<li><<< Inicio</li>
<li><<</li>
<?php
}
for($i = 1; $i <= $pages; $i++) {
$class = $set == $i ? "active" : "";
?>
<li class="<?php echo $class; ?>"><?php echo $i; ?></li>
<?php
}
if($set < $pages) {
?>
<li>>></li>
<li>Último >>></li>
<?php
}
?>
</ul>
<?php
}
unset($array["totalCount"]);
return $array;
}
you can try displaying it as a dropdown between the 'next' and 'prev' button if you want.. it would be easier to display all the page numbers..
or you can first get the value of current page, add 5 and store it as '$add' and minus 5 and store it as '$minus' then insert this in the page buttons:
<input type="submit" value="<?php echo $page_num;?>" <?php if($pagenum > $add || $pagenum < $minus){ echo "style='display:none'";?>>
it will hide the buttons that are more than 5 and less than 5 the current page
replace yor 'for' with this:
$get_add = $params["set"] + 5;
$get_minus = $params["set"] - 5;
for($i = 1; $i <= $pages; $i++) {
$class = $set == $i ? "active" : "";
?>
<li class="<?php echo $class; ?>" <?php if($i > $get_add || $i < $get_minus){ echo "style='display:none;position:absolute'";?>><?php echo $i; ?></li>
<?php
}

Display images with pagination from mysql

I had a php page to display images from a mysql database. It displays all the images uploaded in 1 page one after the other. How can i display 5 or 6 images per page with pagination?
Here is my php page.
<?Php
include("init.php");
include("template/header.php");
?>
<div class="view_albums"><h3> View Albums </h3>;
<?php
$album_id = $_GET['album_id'];
$images = get_images($album_id);
if (empty($images)) {
echo 'There are no images ';
} else {
foreach ($images as $image) {
?> <div class="box"> <?php
echo ' <img class="box1" src="uploads/thumbs/', $image['album'], '/', $image['id'], '.', $image['ext'], '" title="Uploaded on ', date('l F j, Y \a\t g:i A',$image['timestamp']),'"> [delete]';
?> <?php
}
}
?>
</div>
</div>
<?php
include("template/footer.php");
?>
try to use the below pagination function
function genPagination($total,$currentPage,$baseLink,$nextPrev=true,$limit=10)
{
if(!$total OR !$currentPage OR !$baseLink)
{
return false;
}
//Total Number of pages
$totalPages = ceil($total/$limit);
//Text to use after number of pages
$txtPagesAfter = ($totalPages==1)? " page": " pages";
//Start off the list.
$txtPageList = '<br />'.$totalPages.$txtPagesAfter.' : <br />';
//Show only 3 pages before current page(so that we don't have too many pages)
$min = ($page - 3 < $totalPages && $currentPage-3 > 0) ? $currentPage-3 : 1;
//Show only 3 pages after current page(so that we don't have too many pages)
$max = ($page + 3 > $totalPages) ? $totalPages : $currentPage+3;
//Variable for the actual page links
$pageLinks = "";
//Loop to generate the page links
for($i=$min;$i<=$max;$i++)
{
if($currentPage==$i)
{
//Current Page
$pageLinks .= '<b class="selected">'.$i.'</b>';
}
else
{
$pageLinks .= ''.$i.'';
}
}
if($nextPrev)
{
//Next and previous links
$next = ($currentPage + 1 > $totalPages) ? false : 'Next';
$prev = ($currentPage - 1 <= 0 ) ? false : 'Previous';
}
return $txtPageList.$prev.$pageLinks.$next;
}
think it will help you

pagination count range of products on current page

The pagination here works fine, but addition to pagination, as the limit per page is 3 suppose total 8 items in database so i want to display "
showing 1 t0 3 item of 8" on page one, "showing 4 to 6 items of 8" on page two and so on. please help
$recordsLimit = 3;
$page = isset($_GET['page']) ? intval($_GET['page']): 1;
$totalProducts = countProducts($selectedCategoryId);
$totalPages = ceil($totalProducts / $recordsLimit);
$pageNumber = $recordsLimit * ($page - 1);
$products = getProductsByCatId($selectedCategoryId, $pageNumber, $recordsLimit);
<?php if($totalProducts > $recordsLimit) : ?>
<div class="pagination">
<span>Page <?php echo $page.' of '.$totalPages; ?></span>
<?php for($i=1; $i <= $totalPages; $i++) :
if($i == $page) { ?>
<strong><?php echo $i; ?></strong>
<?php } else { ?>
<?php echo $i; ?>
<?php }
endfor; ?>
<?php endif; ?>
Try:
echo "Showing ".( $page == 1 ? 1 : ($page -1) * $recordsLimit +1 )." to ".($page * $recordsLimit)." item of ".$totalProducts;
Simply use this:
<?php $firstNum = (($page-1)*$recordsLimit+1) ?>
showing <?php echo $firstNum; ?> to <?php echo $firstNum+2;?> items of <?php echo $totalProducts;?>
To fix the problem with Tom's code where the last page has an incorrect "to" number I added an offset variable. For this to work the $recordsLimit variable has to match the "showposts" argument in the query. The OP did not show his query so I'm showing the one I used.
$total_results = $wp_query->found_posts;
$recordsLimit = 10;
$args['post_type'] = 'listings';
$args['showposts'] = $recordsLimit;
$args['paged'] = $paged;
$wp_query = new WP_Query($args);
$page = (get_query_var('paged')) ? get_query_var('paged') : 1;
$countoffset = ($page * $recordsLimit)-($total_results);
$countfrom = ( $page == 1 ? 1 : ($page -1) * $recordsLimit +1 );
$countto = ($page * $recordsLimit);
if(($total_results - $countfrom) < $recordsLimit) {$countto = ($countto - $countoffset);}
echo 'Showing '.$countfrom.' to '.$countto.' of '.$total_results.' total results';

Categories