I'm using bootstrap in the whole document, I'm using it for the pagination too.
This link is awesome: PHP & MySQL Pagination
and it helped me a lot coding the method for pagination (I am using postgre, I changed a few things).
When I print each button for the pagination, I am using bootstrap's code:
http://www.w3schools.com/bootstrap/bootstrap_pagination.asp
<ul class=\"pagination pagination-sm\">$links</ul>
and:
$links .= ($i != $page ) ? "<li><a href='$explode[0]$final$i'>$i</a><li> " : "";
for concatenating new strings to the $links variable(of course first this then echoing $links).
Note: I am using explode() because I get my URL and I fix the the &page=
My question is:
How do I shorten the number of buttons to show per page?
At the moment my situation is the one in the screenshot.
I'd love to get something like:
[current][2][3][4][5]...[61][62]
EDIT:
I changed the code to have the "current":
if ($i != $page) {
$links.="<li><a href='$explode[0]$final$i'>$i</a><li>";
} else {
$links.="<li class=\"active\"><a href='#'>current</a><li>";
}
}
EDIT:
added new image thanks to 1st solution (it is now black because I changed theme in the meantime).
EDIT: adding the php code.
$perPage = addslashes(strip_tags(#$_GET["perPage"]));
$page = addslashes(strip_tags(#$_GET['page'])) ?: '1';
$startAt = $perPage * ($page - 1);
SWITCH ($direction){
case "SENT":
$count = "SELECT count(*) as total, 'SENT' as direction FROM sent WHERE date >= '$fdate' AND date <= '$tdate' AND identification LIKE '%$identification%' ";
$query = "SELECT *,'SENT' as direction FROM sent WHERE date >= '$fdate' AND date <= '$tdate' AND identification LIKE '%$identification%' ";
break;
}
$res = pg_fetch_assoc(pg_query($conn, $count));
$total = ceil($res['total'] / $perPage);
if (empty($total1)) { $total1 = '0'; } else { $total1 = ceil($res['total1'] / $perPage); }
$totalPages = $total + $total1;
$links = "";
$absolute_url = full_url( $_SERVER );
for ($i = 1; $i <= $totalPages; $i++) {
$explode = explode("&page=", $absolute_url);
$final="&page=";
if ($i != $page) {
$links.="<li><a href='$explode[0]$final$i'>$i</a><li>";
} else {
$links.="<li class=\"active\"><a href='#'>current</a><li>";
}
}
$query .= "order by date DESC OFFSET '$startAt' LIMIT '$perPage' ";
$result = pg_query($conn, $query);
EDIT:
Found the problem in the jquery:
it will not load, never, but when I call the function at the document=ready status, it will.
<script>
$(document).ready(function(){
$('#paginateblock').css('margin-left','-110px');
});
</script>
I need this to work always, not only when the document is "ready", rather, at every click on 'paginateblock' or everytime I change page.
Anybody can help?
SOLUTION #1:
Thanks to the help of S Gandhe that provided me his code, I'm copying it here with my correction.
for ($i = 1; $i <= $totalPages; $i++) {
if($page >= 7){
$start = $page -4;
} else {
$start = $i;
}
$end = ($start + 7 < $totalPages)?($start + 7):$totalPages;
for ($start; $start <= $end ; $start++) {
$explode = explode("&page=", $absolute_url);
$final="&page=";
$css_class = ($page == $start ) ? "class='active'" : "";
$links .= "<li><a href='$explode[0]$final$start'>$start</a><li>";
}
}
CSS: [the css for <li> did not change]
#page-selection{
width:350px;
height:36px;
overflow:hidden;
}
HTML/PHP
<div id="page-selection"><?php echo "<ul class=\"pagination pagination-sm\">$links</ul>"; ?></div>
SOLUTION #2 - FINAL:
I modified the code a bit more, the pagination buttons are inside a <div> and the content is aligned.
Plus, Page #1 and #lastpage are always shown.
CODE:
for ($i = 1; $i <= $totalPages; $i++) {
if($page >= 4){
$start = $page -3;
} else {
$start = $i;
}
$end = ($start + 6 < $totalPages)?($start + 6):$totalPages;
for ($start; $start <= $end ; $start++) {
$explode = explode("&page=", $absolute_url);
$final="&page=";
$css_class = ($page == $start ) ? "class='active'" : "";
$links .= "<li><a href='$explode[0]$final$start'>$start</a></li>";
}
$firstpage = "<li><a href='$explode[0]$final'1><<</a></li>";
$lastpage = "<li><a href='$explode[0]$final$totalPages'>>></a></li>";
}
HTML:
<div id="page-selector">
<div class="page-selector-field"><?php echo "<ul class=\"pagination pagination-sm\">$firstpage</ul>"; ?></div>
<div id="page-selection" class="page-selector-field"><?php echo "<ul class=\"pagination pagination-sm\">$links</ul>"; ?></div>
<div class="page-selector-field"><?php echo "<ul class=\"pagination pagination-sm\">$lastpage</ul>"; ?></div>
</div>
CSS:
#page-selection{
width:344px;
height:36px;
overflow:hidden;
}
#page-selector{
width: 450px;
height:36px;
overflow:hidden;
/*margin: 0 auto; uncomment this if you want this bar centered */
}
.page-selector-field{
width:50px;
height:36px;
overflow:hidden;
float: left;
}
ul.pagination {
display: inline-block;
padding: 0;
margin: 0;
}
ul.pagination li {
display: inline;
width: 50px;
}
ul.pagination li a {
display: block;
width: 50px;
text-align:center;
float: left;
padding: 8px 16px;
text-decoration: none;
}
am not sure about the quality/performance of code, but you can do it multiple ways, 2 of them here.
I actually started using lazy load and auto loading of pages when scroll rather page numbers, so I don't have the code.
1) JS/CSS:You can create a fix width div for page numbers and scroll to current page using current page number * each div width.
let's say your current page is 54 and each page number is taking 50px. you will set the margin left to -2000px something.
$('#paginateblock').css('margin-left','-110px');
https://jsfiddle.net/66wy0t19/3/
2) PHP : as you said you have the links in array. you can use array_splice to get just the 10 links based on current page number. so if it's 54. you will may be spice it from 50-60 for showing 10.
now you will need 2 buttons. one to move the page numbers div and second to get to Next page (like 4th from 3rd).
Update:
Couldn't find the js code, but here is some code based on php solution.
one minor advantage is you won't print all 100 items on page rather just print 5 links.
echo "<ul class='pagination wrap'>";
if ($this->pageNumber - 1) {
echo "<li ><a href='{$this->url}/page_" . ($this->pageNumber - 1) . "/' {$ajax_request}><<</a></li>";
}
$start =($this->pageNumber > 5)?$this->pageNumber -4:1;
$end = ($i + 5 < $this->total_pages)?($start+5):$this->total_pages;
for ($start; $start <= $end ; $start++) {
echo "<li {$css_class}><a href='{$this->url}/page_{$i}/' {$ajax_request} >{$i}</a></li>";
}
if ($this->total_pages - $this->pageNumber > 1) {
echo "<li ><a href='{$this->url}/page_" . ($this->pageNumber + 1) . "/' {$ajax_request}>>></a></li>";
}
echo "</ul>";[![the output looks like this. ofcourse with classes. but i use bootstrap too.][1]][1]
Update 2:
Assuming each page number is taking 50px. this should work.
var currentPage =27;
var paginateBlockMargin = (Math.ceil(currentPage/2) * 100)-100;
$('#paginateblock').css('margin-left', '-'+paginateBlockMargin+'px');
Check t https://jsfiddle.net/66wy0t19/14/
This is the PHP code using your variables. You would need to replace your for loop with following. Prefer PHP code, as you will still need a lot of consideration in above JS. I wish I could find that JS code I had. sad.
if($page > 5){
$start = $page -4;
}
$end = ($start + 5 < $totalPages)?($start + 5):$totalPages;
for ($start; $start <= $end ; $start++) {
$explode = explode("&page=", $absolute_url);
$final="&page=";
$css_class = ($page == $start ) ? "class='active'" : "";
$links .= "<li><a href='$explode[0]$final$start'>$start</a><li>";
}
Related
I am trying to read data from the WordPress database table and display it on my website. This is my pagination script and I am able to get all the data. The limit and number of rows per page are all fine. When I change pages, I still see the first page but the url changes. Please how do I handle this? Thank you
<?php
global $wpdb;
$er = $wpdb->show_errors();
$result = $wpdb->get_results("SELECT * FROM koh_user");
// number of rows to show per page
$rowsperpage = 10;
// find out how many rows are in the table
$numrows = $wpdb->num_rows;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
// cast var as int
$page = (int) $_GET['page'];
} else {
// default page num
$page = 1;
}
// the offset of the list, based on current page
$offset = ($page - 1) * $rowsperpage;
// get the info from the db
$result = $wpdb->get_results("SELECT CONCAT( koh_user.fname, ' ', koh_user.lname) as name, koh_user.id as id, koh_user.username as username from koh_user LIMIT $rowsperpage OFFSET $offset
");
// Display the rows
echo "<style>";
echo "body {font-family: Arial;}";
echo ".table_container { padding: 10px 12px 0px 12px; border: 1px solid #ccc; }";
echo ".table_container th { background-color:lightblue; color:black; font-weight:bold; border-left: 1px solid white;}";
echo "</style></head>";
echo "<body>";
echo "<div class=\"table_container\"><table>";
echo "<tr><th style=\"padding-left:10px;\">Nom</th><th>Nom d'utilisateur</th><th>Role</th><th></th></tr>";
foreach ($result as $row) {
echo "<tr class ='info'>
<td>" . $row->name . "</td>
<td>" . $row->username . "</td>
<td>" . $row->role . "</td>
<td>
</td>
</tr>"
;}
echo "</table></div>";
// loop to show links to range of pages around current page
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($page > 1) {
// show << link to go back to page 1
echo " <a href='/?page_id=347?page=1'><<</a> ";
// get previous page num
$prevpage = $page - 1;
// show < link to go back to 1 page
echo " <a href='/?page_id=347?page=$prevpage'><</a> ";
} // end if
// loop to show links to range of pages around page
for ($x = ($page - $range); $x < (($page + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on page...
if ($x == $page) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='/?page_id=347?page=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($page != $totalpages) {
// get next page
$nextpage = $page + 1;
// echo forward link for next page
echo " <a href='/?page_id=347?page=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='/?page_id=347?page=$totalpages'>>></a> ";
} // end if
?>
This question already has answers here:
Simple PHP Pagination script [closed]
(3 answers)
Closed 4 years ago.
I'm selecting data from database and I want to limit result by X amount and then show the number of rows left and showing button below to navigate to next page of the result (continues until there's no more result in database).
How do i do this.
my code is only fetching it...but how do I add the page 1,2,3,4,5
something like stackOverflow tags page
my code:
<?PHP
$SQL = "SELECT * FROM $tags_table LIMIT 20";
$Q = queryDB($SQL);
if (mysqli_num_rows($Q)) {
while ($row = mysqli_fetch_assoc($Q)) {
$tag_id= $row['tag_id'];
$details = $row['details'];
$tagName= $row['tag_name'];
$HTML_temp = "<div class='grid-view page-cell'>
<div class='page-header'><a href='#' class='post-page'>{$tagName}</a></div>
<div class='details'>{$details}</div>
</div>";
ECHO $HTML_temp;
}
}
?>
I created an answer to this feature. Below are my code for future use.
PHP:
<?PHP
//count the number of rows in db
function countTags(){
global $conn, $tags_table;
$SQL = "SELECT COUNT(tag_id) FROM $tags_table";
return mysqli_fetch_array(queryDB($SQL))[0];
}
//Pager:
//Show next pages box if $options["NumOfRecords"] is greater than 20
//We fetching 20 records per page -- Adjust to your needs
function pager(array $options = array()){
$options = array_merge(array(
'NumOfRecords' => 0, //number of records from database
'maxPager' => 5, //number pager to show eg. 1-5
'maxPageRecords' => 20 // since I need 20 records maximum per/page
),$options);
$rows = (int) $options['NumOfRecords'];
$maxPager = (int) $options['maxPager'];
$maxPageRecords = (int) $options['maxPageRecords'];
//offset records
$offset = $rows - $maxPageRecords; //since our max records per page is 20
$totalPages = ceil($rows/$maxPageRecords); //move it to neart heigher number
$numOfPagesLeft = $totalPages-1; //pages left
if ($numOfPagesLeft) {
//check if tab_id is set
$tab_id = $activePage = isset($_GET['tab_id']) && (int)$_GET['tab_id'] ? (int)$_GET['tab_id']:1;
//store pager here
$pagerArray = array();
//url to page we working on
$URL = DOMAIN().'/'.(IsadminLogin() ? ("apps/tags/") :"tags/");
$i = 0; //pager counter
for ($row=0; $row < $numOfPagesLeft; $row++ ) {
$i++;
//show only five pager
if ($offset && $i <= $maxPager && $activePage !== $totalPages && $totalPages != $tab_id) {
$page_id = $tab_id++;
$href = $URL .$page_id;
$active = ($activePage == $page_id ? "current":"random");
$ellipse = ($i== $maxPager && $tab_id !== ($offset/$maxPageRecords) ? "<span class='page-numbers dots'>...</span>":"");
$pagerArray[] = "<a class='page-numbers {$active}' href='{$href}/'>{$page_id}</a>{$ellipse}";
}
}
//add previous page
if ($activePage > 1) {
//previous pagers
$prev = $activePage -1;
$prevHref = $URL .$prev;
$prevPagers = $activePage > 2 ? "<a class='page-numbers prv' href='{$URL}1'>1</a><span class='page-numbers dots'>...</span>":"";
array_unshift($pagerArray , "<a class='page-numbers prev' href='{$prevHref}/'>prev</a>{$prevPagers}");
}
//show next button if offset is true
if ($numOfPagesLeft) {
//next pagers
$next = $activePage +1;
$nextHref = $URL.$next;
$lastPager = $totalPages;
$PagerLast = $URL.$lastPager;
$active = ($activePage == $lastPager ? "current":"random");
$pagerS = $lastPager ? "<a href='{$PagerLast}' class='page-numbers {$active}'>{$lastPager}</a>":"";
array_push($pagerArray , $totalPages != $tab_id ? "{$pagerS} <a class='page-numbers prev' href='{$nextHref}/'>next</a>":"{$pagerS}");
}
//implode pager
return join('',$pagerArray);
}
}
$maxPageRecords = 20; //since we fetching 20 records/page
$tab_id = isset($_GET['tab_id']) && (int)$_GET['tab_id'] > 0 ? (int)$_GET['tab_id']:1;
$offset = $tab_id == 1 ? 0:($tab_id > 1 ? ($tab_id-1) *$maxPageRecords:0);//calculate offset for SQL
$SQL = "SELECT * FROM $tags_table LIMIT {$maxPageRecords} OFFSET {$offset}";
$Q = queryDB($SQL);
$NR = mysqli_num_rows($Q);// number of rows returned
if ($NR) {
while ($row = mysqli_fetch_assoc($Q)) {
$tag_id = $row['tag_id'];
$details = $row['details'];
$TagName = $row['tag_name'];
$HTML_temp = "<div class='grid-view tag-cell'>
<div class='excerpt-header'><a href='#' class='post-tag'>{$TagName}</a></div>
<div class='excerpt'>{$details}</div>
</div>";
ECHO $HTML_temp;
}
}else{
ECHO "No tags found in database";
}
//echo $offset;
//GET current domain name
$LOCALIP = array('127.0.0.1','::1');
$sitename = "school";
$HostStatus = !in_array(GET_IP(), $LOCALIP)? TRUE:FALSE; //hosting local or remote server
function DOMAIN(){global $HostStatus,$sitename;if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') { $domain = 'https://'.str_replace(array('https://www.','http://www.','www.'), '', ($_SERVER['SERVER_NAME'])).($HostStatus ? '':'/'.$sitename);}else {$domain = 'http://'.str_replace(array('https://www.','http://www.','www.'), '', ($_SERVER['SERVER_NAME'])).($HostStatus ? '':'/'.$sitename);} return $domain;}function GET_IP(){if (!empty($_SERVER['HTTP_CLIENT_IP'])) {$ip=$_SERVER['HTTP_CLIENT_IP'];}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];}else{$ip=$_SERVER['REMOTE_ADDR'];}return $ip;}
?>
HTML:
Lets call pager() function
<div class='pager'>
<div class='col-lg-12 no-padding'>
<div class='col-lg-2'></div>
<div class='col-lg-4'></div>
<div class='col-lg-6 no-padding'>
<div class="pager rfloat">
<?PHP
//call pager() on the button of the page u want to show pagwer boxes
ECHO pager(array(
'maxPageRecords'=>20,
'NumOfRecords'=>countTags(), //records could be any number e.g. 400,200,52,12..make sure its coming from DB
'maxPager'=>5));
?>
</div>
</div>
</div>
</div>
CSS:
.pager a{
display: inline-block;
padding: 4px 8px;
font-size: 12px;
color: #848d95;
border: 1px solid #e4e6e8;
border-radius: 3px;
background-color: transparent;
margin-left: 5px;
}
.page-numbers.current,.page-numbers:hover{
transition: all ease-in-out .2s;
color: #FFF;
background-color: #ff7308;
border-color: transparent;
}
.page-numbers.dots{
color: #848d95;
background-color: transparent;
border-color: transparent;
box-shadow: none;
padding:0 15px;
letter-spacing: 3px;
}
I can't seem to find the answer anyway so guess I need to ask at least I did try google anyway I am making a group feature similar to the one facebook has got but not as good since i'm the only one developing this but over time it get better.
Anyway,
how can I make this code limit the pagination numbers? for example if there is loads of results in the database I only want to first 10 to be displayed after that use dots so they can click and go more in depth if they want to so when the click the dot they get another 10 results so 20-30 will then be displayed as pagination. I don't need it exactly like this but some way to limit the ammount of numbers being displayed at a time.
Here;s the code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
#content
{
width: 900px;
margin: 0 auto;
font-family:Arial, Helvetica, sans-serif;
}
.page
{
float: right;
margin: 0;
padding: 0;
}
.page li
{
list-style: none;
display:inline-block;
}
.page li a, .current
{
display: block;
padding: 5px;
text-decoration: none;
color: #8A8A8A;
}
.current
{
font-weight:bold;
color: #000;
}
.button
{
padding: 5px 15px;
text-decoration: none;
background: #333;
color: #F3F3F3;
font-size: 13PX;
border-radius: 2PX;
margin: 0 4PX;
display: block;
float: left;
}
</style>
</head>
<body>
<div id="content">
<?php
error_reporting(0);
$query1=mysql_connect("localhost","root","");
mysql_select_db("freeze_demo",$query1);
error_reporting(0);
$start=0;
$limit=1;
if(isset($_GET['id']))
{
$id=$_GET['id'];
$start=($id-1)*$limit;
}
$query=mysql_query("select * from pagination LIMIT $start, $limit");
echo "<ul>";
while($query2=mysql_fetch_array($query))
{
echo "<li>".$query2['text1']."</li>";
}
echo "</ul>";
$rows=mysql_num_rows(mysql_query("select * from pagination"));
$total=ceil($rows/$limit);
if($id>1)
{
echo "<a href='?id=".($id-1)."' class='button'>PREVIOUS</a>";
}
if($id!=$total)
{
echo "<a href='?id=".($id+1)."' class='button'>NEXT</a>";
}
echo "<ul class='page'>";
for($i=1;$i<=$total;$i++)
{
if($i==$id) { echo "<li class='current'>".$i."</li>"; }
else { echo "<li><a href='?id=".$i."'>".$i."</a></li>"; }
}
echo "</ul>";
?>
</div>
</body>
</html>
Just basically need to update it for the future when my database or a certain group gets bigger.
Thanks
<?php
function custom_pagination($page, $totalpage, $link, $show) //$link = '&page=%s'
{
//show page
if($totalpage == 0)
{
return 'Page 0 of 0';
} else {
$nav_page = '<div class="navpage"><span class="current">Page '.$page.' of '.$totalpage.': </span>';
$limit_nav = 3;
$start = ($page - $limit_nav <= 0) ? 1 : $page - $limit_nav;
$end = $page + $limit_nav > $totalpage ? $totalpage : $page + $limit_nav;
if($page + $limit_nav >= $totalpage && $totalpage > $limit_nav * 2){
$start = $totalpage - $limit_nav * 2;
}
if($start != 1){ //show first page
$nav_page .= '<span class="item"> [1] </span>';
}
if($start > 2){ //add ...
$nav_page .= '<span class="current">...</span>';
}
if($page > 5){ //add prev
$nav_page .= '<span class="item">«</span>';
}
for($i = $start; $i <= $end; $i++){
if($page == $i)
$nav_page .= '<span class="current">'.$i.'</span>';
else
$nav_page .= '<span class="item"> ['.$i.'] </span>';
}
if($page + 3 < $totalpage){ //add next
$nav_page .= '<span class="item">»</span>';
}
if($end + 1 < $totalpage){ //add ...
$nav_page .= '<span class="current">...</span>';
}
if($end != $totalpage) //show last page
$nav_page .= '<span class="item"> ['.$totalpage.'] </span>';
$nav_page .= '</div>';
return $nav_page;
}
}
//using
if(isset($_GET['page'])) {
$page = $_GET['page'];
} else {
$page = 1;
}
$sql = "SELECT count(*) AS total FROM post ORDER BY idpost DESC"; //please select COUNT is fast
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
$show = 5; //Show 5 result per page
$totalpage = ceil($rows['total'] / $show); //Total page
$start = ($page * $show) - $show; //Start result
$yourQuery = "SELECT * FROM post ORDER BY id LIMIT $start, $show";
//Query and show here
//Show pagination
echo custom_pagination($page, $totalpage, 'index.php?action=detail&page=%s', $show);
?>
Given that $id is a page number (perhaps refactor this to be $page so it it recognised as a page number, rather an a unique id of a particular record), you would change the final for loop to be a bit more restrictive.
For example, instead of starting at 1, start from 5 pages before the current page. And instead of ending at $total, end at 5 pages after the current page.
$start = $id - 5.
if ($start < 1) {
$start = 1;
}
$end = $id + 5;
if ($end > $total) {
$end = $total;
}
for ($i = $start; $i <= $end; $i++) {
// echo pagination options
}
You could also modify this to give links that will get you closer to where you want to go (i.e. if displaying pages 20 to 30, of 100 pages, show links for pages 10, 40, 50 and 60, or even supply an input box to let you jump to a specific page.
I was able to get my pagination script working, and everything works fine except when you go to PAGE 2, you can see a PAGE 0, which if you click on it give you nothing.
I need to fix my current code so that the application does not show a PAGE 0.
Here is the necessary code:
<?php
$total_records = countRecords(); // self explanatory function called here
$total_pages = ceil($total_records / $rec_limit);
$adjacents = 2;
$previousPage = $page - 1;
$nextPage = $page + 1;
$querystring = "";
$start = ($page < $adjacents ? 1 : $page - $adjacents);
$beginning = 1;
$end = ($page > $total_pages - $adjacents ? $total_pages : $page + $adjacents);
foreach($_GET as $key => $value)
{
if($key != "page") $querystring .= "$key=$value&";
}
echo
'<div class="row-fluid">
<div class="span2">'.countRecords()." total records" .'</div>
<div class="container pagination-small">
<ul style="margin: 3px;" class="pager">';
echo #"<li>First</li>";
if ($left_rec < $rec_limit)
{
$last = $page - 1;
echo #"<li><a href=\"$targetpage?page=$previousPage&$querystring\">
Previous</a></li>";
for($i= $start; $i <= $end; $i++)
{
echo #"<li " . ((($page)==$i)? "class=\"active\"" : "") . ">
$i</li>";
}
}
else if($page == 0)
{
for($i= $start; $i <= $end; $i++)
{
echo #"<li " . ((($page)==$i)? "class=\"active\"" : "") . ">
$i</li>";
}
echo #"<li>Next</li>";
}
else if ($page > 0)
{
$last = $page - 2;
echo #"<li><a href=\"$targetpage?page=$previousPage&$querystring\">
Previous</a></li>";
for($i= $start; $i <= $end; $i++)
{
echo #"<li " . ((($page)==$i)? "class=\"active\"" : "") . ">
$i</li>";
}
echo #"<li>Next<li>";
}
echo #"<li>Last</li>";
echo '<ul></div></div>';
I tried to keep the code as short as possible. If there are any errors, just note it's only a typo as I typed it here. The code works, with exception to my problem.
So with that all said, can anyone tell me how to remove PAGE 0 from the pagination? I have done some research, but I have been unsuccessful applying it to my code. So I'm hoping someone can take a look at my code and tell me how I can alter it to make this work.
I appreciate the help.
Thank you in advance.
Logic flaw:
$start = ($page < $adjacents ? 1 : $page - $adjacents);
If you're on Page 1, you'll get
$start = (1 < 2 ? 1 : 1 - 2);
$start = -1; // page negative one? huh?
Then this loop is pointless:
foreach($_GET as $key => $value) { ... }
Why not just
unset($_GET['page']);
$q = http_build_query($_GET);
I want to limit the number of pages displayed on my pagination php script below. This was a script made a few years back for me, and although I have read through similar problems on here, their coding is very different.
Any help with this would be really appreciated.
Here is my current script:
<?php
if ($max_pages>1) {
echo "<br>";
if ($page>0) {
echo 'Previous';
}
for ($x=0;$x<$max_pages;$x++) {
if ($page<>$x) {
echo ''.($x+1).'';
}
else {
echo '<span class="pagination">'.($x+1).'</span>';
}
}
if (($page+1<>$max_pages)) {
echo 'Next';
}
}?>
Your current script cycles $x between 0 and $max_pages.
What you can do is first replace them with $from_page and $to_page:
$from_page = 0;
$to_page = $max_pages;
...
for ($x=$from_page; $x < $to_page; $x++)
at which point the script will work just as before.
Now if you want to only display from $N pages before to $N pages after $page,
$N = 5; // display 5+5+1 = 11 pages
$from_page = $page - $N; if ($from_page < 0) $from_page = 0;
$to_page = $from_page + 2*$N+1; if ($to_page > $max_pages) $to_page = $max_pages;
$from_page = $to_page - 2*$N-1; if ($from_page < 0) $from_page = 0;
Not the most elegant way perhaps, but it will try to fit an 11-page area centered on the current page. You may want to also display a link to pages 0 and $max_pages-1.
MRE version
<?php
if ($max_pages>1)
{
$N = 5; // display 5+5+1 = 11 pages
$to_page = min($max_pages, max(0, $page - $N) + 2*$N+1);
$from_page = max($to_page - 2*$N-1, 0);
echo "<br>";
if ($page > 0)
{
echo 'Previous';
}
for ($x=$from_page; $x < $to_page; $x++) {
if ($page != $x) {
echo ''.($x+1).'';
}
else {
echo '<span class="pagination">'.($x+1).'</span>';
}
}
if (($page+1<>$max_pages)) {
echo 'Next';
}
}?>