PHP: Trying to come up with a "prev" and "next" link - php

I'm displaying 10 records per page. The variables I have currently that I'm working with are..
$total = total number of records
$page = whats the current page I'm displaying
I placed this at the top of my page...
if ( $_GET['page'] == '' ) { $page = 1; } //if no page is specified set it to `1`
else { $page = ($_GET['page']); } // if page is specified set it
Here are my two links...
if ( $page != 1 ) { echo '<div style="float:left" ><a href="index.php?page='. ( $page - 1 ) .'" rev="prev" >Prev</a></div>'; }
if ( !( ( $total / ( 10 * $page ) ) < $page ) ) { echo '<div style="float:right" ><a href="index.php?page='. ( $page + 1 ) .'" rev="next" >Next</a></div>'; }
Now I guess (unless I'm not thinking of something) that I can display the "Prev" link every time except when the page is '1'. How can make it where the "Next" link doesn't show on the last page though?

replace your last line of code with:
if ($page*10 < $total) echo '<div style="float:right" ><a href="index.php?page='. ( $page + 1 ) .'" rev="next" >Next</a></div>';

!( ( $total / ( 10 * $page ) ) < $page )
I ... don't think this is correct.
Suppose $total is 1000 - then on page 99, 1000/990 is less than 99, but there's still another page to show.
What you probably want is to check whether 10 * $page is greater than or equal to $total.

You need the total divided by the pagecount ($total / 10) with an extra page if there is a remainder. Use the ceil function.
$page < ceil($total / 10)

Pagination is something that comes up so often in web projects, that it's usually best to create some kind of class somewhere, or at least some conveniences functions, that give you everything you need.
Here's a function that would return a dictionary of things that might be useful:
function pagination($numberItems, $perPage, $currentPage) {
$numPages = ceil($numberItems/$perPage);
return array(
'numberPages' => $numPages,
'start' => ($currentPage - 1) * $perPage + 1,
'end' => min($currentPage * $perPage, $numberItems),
'hasNext' => $page != $numPages,
'hasPrev' => $page != 1
);
}

You have a mistake in the last line:
$totalPages = ceil( $total / 10 );
if ( $page < $totalPages ) ) { echo "<div style="float:right" ><a href="index.php?page='. ( $page + 1 ) .'" rev="next" >Next</a></div>"; }

// lets get total number of pages here
$itemsPerPage = 10;
$totalItems = 105; // just for example
$pagesNo = ceil( $totalItems / $itemsPerPage );
// get the current page here...
$current = ( isset($_GET['page']) ) ? (int)$_GET['page'] : 1; // if page is defined, use it, instead use 1
$current = ( $current > 0 ) ? $current : 1; // if page was -1,-2... for instance, use 1
// show us 'Prev' button
echo ( $current > 1) ? "<a href='".($current-1)."'>Prev</a>" : "";
// show current page NO
echo $current;
// show 'Next' button
echo ( $current < $pagesNo) ? "<a href='".($current+1)."'>Next</a>" : "";
Should be like this... This is just quick code... Later, work on some page span (set how many pages should be shown before/after current page number...)

Sounds like you need to detect if you're on the first or the last page and "guard" the code against those conditions.
if (/* not the first page */) {
// print the prev link
}
if (/* not the last page */) {
// print the next link
}
You already have the code to detect if page=1 so now you just need to determine if you're on the last page or not (integer division or ceil() should be the way to go).
For pages of PHP results from SQL, there's a neat article on PHPFreaks http://www.phpfreaks.com/tutorial/basic-pagination

Related

Get numbers next and after a certain number with dynamic max results with PHP

I have a pagination which renders some pages. I have a setting where the user can define how many pages are to be displayed as numbers in the pagination nav. The first and last number are always visible. Now if the user wants to have 3 numbers on the nav and assuming that i am now in the page 7, then it should look like this:
1 ... 6 7 8 ... 12
If the user wants four items then it should look like that:
1 ... 6 7 8 9 ... 12
Up until now i have the following which gives me 3 before and after the current page
$maxLinks = 3;
$currentPageNumber = 7;
$pages = [];
$pages[] = 1;
for($i = max(2, $currentPageNumber - $maxLinks); $i <= min($currentPageNumber + $maxLinks, 12 - 1); $i++) {
$pages[] = $i;
}
$pages[] = 12;
foreach ($pages as $key => $page) {
$newPage = '...';
if (($key === 0) && $pages[1] !== $page + 1) {
array_splice( $pages, 1, 0, $newPage );
}
$itemBeforeLast = count($pages)-2;
if (is_numeric($pages[$itemBeforeLast]) && ($key === $itemBeforeLast) && $pages[$itemBeforeLast + 1] !== $pages[$itemBeforeLast] + 1) {
array_splice( $pages, $itemBeforeLast +1, 0, $newPage );
}
}
This gives me back the following:
But i only want to get 3 or 4 numbers between the dots (this changes based on the value that the user gives in the settings ($maxLinks variable))
Any help is deeply appreciated
Best regards
As you add them to both sides, you need to divide by 2. Also, remove 1 to account for the current page. Then you just need to account for the possibility of having a non-even number of links to the left&right by rounding (down for the left, up for the right).
And end up with:
for($i = max(2, $currentPageNumber - floor(($maxLinks-1)/2));
$i <= min($currentPageNumber + ceil(($maxLinks-1)/2), 12 - 1); $i++)

Show Query Results with WordPress

I have been searching with no luck so sorry if this has been answered before.
I am wanting to show the results of the query with something like " Viewing 1-10 of 100" basically showing the current posts I am viewing and the total post count. If someone can point me in the right direction I would appreciate it very much.
You can insert the following code in the file search.php or anywhere you need.
<?php
function get_number_of_results( $current_page, $total, $jumps = 10){
$first_result = 1;
$start = $first_result;
$end = $jumps;
if($current_page >=2) {
$previous = $current_page - 1;
$first_result = ($previous * $jumps) + 1;
$start = $first_result;
$end = $start + ($total - 1);
}
return "$start - $end";
}
$current_page = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$total = $wp_query->post_count;
// Result
echo "Viewing " . get_number_of_results( $current_page, $total);
?>
Notes
You can move the function to the file functions.php to just call the two las lines of my example.
The line: <?php $total = $wp_query->post_count; ?> retrieve the number of total results.
The variable $current_page retrieve the current page of the results (more info).
The function can jump between the number of pages you only need to specify as third parameter.

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

I am trying to limit the shown pagination. My site has 500+ pages, and all 500+ numbers are shown in the pagination.
I am trying to limit it like this:
Prev 1 2 3 4 5 6 Next
My code:
$skin = new skin('site/pagination'); $pagination = '';
if ($pages >= 1 && $page <= $pages) {
for ($x=1; $x<=$pages; $x++) {
$TMPL['pagination'] = ($x == $page) ? '<strong>'.$x.'</strong> ' : ''.$x.' ';
$pagination .= $skin->make();
}
}
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++)
What do you expect this to do?:
for ($x=1; $x<=$pages; $x++)
It is going to create an entry for every page. If you don't want that, limit it how it makes sense:
for ($x=1; $x <= min(5, $pages); $x++)
Even better would be to consider the current page:
for ($x=max($curpage-5, 1); $x<=max(1, min($pages,$curpage+5)); $x++)
//Let's say you want 3 pages on either side of your current page:
$skin = new skin('site/pagination'); $pagination = '';
$currentPage = get the current page number however you have it stored;
// set the lower bound as 3 from the current page
$fromPage = $currentPage - 3;
// bounds check that you're not calling for 0 or negative number pages
if($fromPage < 1) {
$fromPage = 1;
}
// set the upper bound for what you want
$toPage = $fromPage + 7; // 7 is how many pages you'd like shown
// check that it doesn't exceed the maximum number of pages you have
if($toPage > $maxPages) {
$toPage = $maxPages;
}
// iterate over your range
for ($x=$fromPage; $x<=$toPage; $x++) {
$TMPL['pagination'] = ($x == $page) ? '<strong>'.$x.'</strong> ' : ''.$x.' ';
$pagination .= $skin->make();
}
For large numbers of pages, consider displaying links using "logarithmic" pagination. See my answer here (PHP code included):
How to do page navigation for many, many pages? Logarithmic page navigation
I tried the answers provided by wallyk and Hemang but they fell short for my pagination case. Their answers would sometimes display less links than the range. I had to add some max and min statements.
Here is my take in Javascript code:
var minPage = Math.max(Math.min(currentPage - (range / 2), totalPages - range), 0);
var maxPage = Math.min(Math.max(currentPage + (range / 2), range), totalPages);
The range is the number of links always displayed.
The totalPages is the total number of pages to iterate over.
The currentPage is the currently displayed page.
Note that my pagination index is 0 based.

Can not send levels to switch pages

Am working on array pagination. I am having some trouble forming equations. what I want is when
$CurrentPage = 1 then $Start = 1,
if $CurrentPage = 2 then $Start = 30,
if $CurrentPage = 3 then $Start = 60,
if $CurrentPage = 4 then$Start = 90
and so on..
How do I write the if else block ?
you can also use this:
$Start = ($currentPage==1 ? 1 : ($currentPage-1)*30);
and forget all the if/else.
If the current page is one, display from result one (for what ever reason not from result 0), if page bigger than one display from result (page - 1)*30
if ((int)$currentPage > 1) {
$start = ($currentPage - 1)*30;
}
else {
$start = 1;
}
or in a shorter way
$start = ($currentPage > 1) ? ((int)$currentPage - 1) * 30 : 1;
Keep it simple:
$Start = max(1, ($currentPage-1) * 30);

PHP Pagination - having trouble detecting pages

I want to make a minimalistic pagination script that basically does three things:
On first page, just a next button.
On last page, just a previous button.
For all others in between, both.
I have most of the code worked out, but I'm just making some if/elseif statements that determine which page the user is on and I'm having a bit of trouble. (those at bottom) First, here's the query code:
$per_page = 10;
$pages_query = mysql_query("SELECT COUNT(idnum) FROM images");
$pages = ceil(mysql_result($pages_query, 0) / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page'] :1;
$start = ($page -1) * $per_page;
$query = mysql_query("SELECT * FROM images ORDER BY idnum DESC LIMIT $start, $per_page");
And here's the if statement part:
$nextend = $pages - 1;
$next = $page + 1;
$previous = $page - 1;
if ($pages >= 1 && $page = 1) {
echo 'next';
} elseif ($pages >= 1 && $page = 2) {
echo 'previous';
}
It always results in the next button, no matter what page I'm on. How do I detect the page number so I can display the pagination buttons the way I want to? By the way, I know I don't have the else statement for the middle pages (next and previous) yet.
You are assigning in your if statements rather than comparing. You don't want this in your if statement:
$page = 1
That just assigns 1 to $page.
You want this:
$page == 1
Or this:
$page === 1
$nextend = $pages - 1;
$next = $page + 1;
$previous = $page - 1;
$maxpages = ? //You need to have a variable with the last page number
if ($pages > 1) {
echo 'previous';
}
if ($page < $maxpages) {
echo 'next';
}
I don't understand what logic you are trying to do with your if/else statements, also when checking if a variable is equal to a number/other variable your "==" not "="
What you've got to do is way simple:
If you're not on the first page, you always have to show a back button.
If you're not on the last page you always have to show a next button.
Please note that both those conditions can happen at the same time so using an elseif between them won't work as it will only allow one of them to execute.
Example:
if ( $page > 1 )
{
echo( "Previous" );
}
if ( $page < $pages )
{
echo( "Next" );
}

Categories