PHP pagination Adjacents - php

I was able to create a working pagination system for my application. But the problem I am having is when a user does a search, it can/will display over 100 pages in the pagination.
I am trying to figure out how to show only like 5 on each side of the current page. I would like to create a FIRST page button, and a LAST page button, but I'll deal with that later.
So here is the first part of code that counts the records in the database table:
<?php
function countRecords()
{
// The application takes a lot of user input, which then builds a query here.
// The user input goes into a session variable called $_SESSION['where']
// I'll start with the actual query code
$sql = "SELECT COUNT(DISTINCT CONTAINER_NUMBER) AS TOTAL
FROM 'contTable'" . " WHERE (" . $_SESSION['where'] . ");";
$sqlres = #mysql_query($sql) or die();
$row = mysql_fetch_row($sqlres);
$return $row[0];
}
So code above gets the count from the table depending on the search criteria.
Here is the next piece of code that prints the grid. I'll keep it as short as possible:
function displayrecords()
{
$rec_limit = 100;
$targetpage = "containers.php";
if(isset($_GET['page']))
{
$page = $_GET['page'];
$offset = $rec_limit * ($page - 1);
}
else
{
$page = 1;
$offset = $rec_limit * ($page - 1);
}
$left_rec = countRecords() - ($page * $rec_limit);
$select = "";
$_SESSION['where'] = "";
// user input variables are here that build a variable called $_SESSION['where']
// I'll skip the code down to the query
if ($_SESSION['where'] != "") $select = "SELECT * FROM 'contTable'" . " WHERE
(" . $_SESSION['where'] . ") GROUP BY container, bol LIMIT " . $offset . ",
" . $rec_limit . ";";
}
Please excuse any typos or missing brackets and whatnot. Just know the above code works.
Now here is the code for the rest of the pagination:
$total_records = countRecords();
$total_pages = ceil($total_records / $rec_limit);
$adjacents = 5; // I just added this variable. I don't know what to do with it
$previousPage = $page - 1;
$nextPage = $page + 1;
$querystring = "";
foreach ($_GET as $key => $value)
{
if ($key != "page") $querystring .= "$key=$value&";
}
echo '<ul style="border: 0px solid red; margin: 3px;" class="pager">';
if ($left_rec < $rec_limit)
{
$last = $page - 2;
echo #"<li><a href=\"$targetpage?page=$previousPage&$querystring\">
Previous</a></li>";
for($i = 1; $i <= $total_pages; $i++)
{
echo #"<li " . ((($page+1)==$i)? "class=\"active\"" : "") . ">
$i</li>";
}
}
else if ($page == 0)
{
for($i = 1; $i <= $total_pages; $i++)
{
echo #"<li " . ((($page+1)==$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 = 1; $i <= $total_pages; $i++)
{
echo #"<li " . ((($page+1)==$i)? "class=\"active\"" : "") . ">
$i</li>";
}
echo #"<li>Next</li>";
}
echo '</ul>';
}
So, with all of the code above, I can display a grid, and display the pages at the bottom of the application. But I don't want to show all 100 pages, only 5 on each side of the current page. I know I need to utilize the variable called $adjacents and plug it in to the paging portion of the code. But I'm not exactly sure how to do it.
I hope I am being clear on my request.
Please help.

Instead of looping through all of the pages:
for($i = 1; $i <= $total_pages; $i++)
Try doing something like this:
$start = ($page < $adjacents ? 1 : $page - $adjacents);
$end = ($page > $total_pages - $adjacents ? $total_pages : $page + $adjacents);
for($i= $start; $i <= $end; $i++)
//Here you can loop through the numbers within adjacents of the current page

Related

Pagination Prev - Next Increment

i create a php news system, but i have a problem:
<?php
include('config.php');
if( isset( $_GET["page"]) ) $PAGE=$_GET["page"]; else $PAGE=1;
$query1=mysql_query("select id, name, email , age from addd LIMIT ". (($PAGE * 5) - 5) .",5");
echo "<table><tr><td>Testo</td><td>Nome</td><td>Anni</td></tr>";
function truncate_string($str, $length) {
if (!(strlen($query2['name']) <= $length)) {
$query2['name'] = substr($query2['name'], 0, strpos($query2['name'], ' ', $length)) . '...';
}
return $query2['name'];
}
while($query2=mysql_fetch_array($query1))
{
$number= $query2['name'];
echo "<tr><td>".substr($query2['name'], 0, 500)."...</td>";
echo "<td>".$query2['email']."</td>";
echo "<td>".$query2['age']."</td>";
echo "<td>".str_word_count($number)."</td>";
echo "<td><a href='edit.php?id=".$query2['id']."'>Mod</a></td>";
echo "<td><a href='delete.php?id=".$query2['id']."' onclick=\"return confirm('Sei sicuro di volerlo eliminare?');\");'>Canc</a></td><tr>";
echo "<td><a href='singletwo.php?id=".$query2['id']."');'>vedi</a></td<tr>";
}
?>
The pages follow this numbering: ?page=1, ?page=2 ecc.
Each page contains 5 news.
How do I create an automatic pagination system?
With Prev-Next, automatically detect possible next or previous pages?
I don't know how to do it.
Start by having the max length and total number of rows in variables:
<?php
include('config.php');
$max = 5;
$total = mysql_query("select count(*) from addd");
$PAGE = isset($_GET["page"]) ? $_GET["page"] : 1;
$query1 = mysql_query("select id, name, email , age from addd LIMIT " . (($PAGE * $max) - $max) . "," . $max);
That way, you can calculate how many pages you'll need.
The following code will give you a page list (Page 1, Page 2, Page 3 etc.):
for($i = 0; $i < ceil($total / $max); $i ++)
{
$p = $i + 1;
echo 'Page ' . $p . '';
}
If you'd rather have Previous and Next links, try this:
if($PAGE > 1)
echo '<a href="?page=' . ($PAGE - 1) . '>Previous</a>';
if(ceil($total / $max) > $PAGE)
echo '<a href="?page=' . ($PAGE + 1) . '>Next</a>';
What you could do is:
$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = $currentPage*5;
$offset = $offset-5;
Now that you have these numbers, you can use them in your query:
$stmt = "SELECT
...
FROM news
LIMIT ".$offset.", ".$limit.";
This way you'll get the records you want. As far as the next and previous buttons go:
if ($currentPage > 1) {
// Show previous button
}
For the next button you'll need to do another query:
$stmt = "SELECT COUNT(*) as total FROM news";
$result = $pdo->fetch();
$totalRows = $result['total'];
if ($currentPage < round($totalRows/5)) {
// Show next button
}

PHP pagination page zero issue

My pagination is showing a page zero (0) when you go to page 2. Not sure why. I don't want to show a page zero.
I'll try to only show the necessary code.
Here is my code:
<?php
$rec_limit = 100;
$targetpage = "dispatch.php";
if (isset($_GET['page']))
{
$page = $_GET['page'];
$offset = $rec_limit * ($page - 1);
}
else
{
$page = 1;
$offset = 0;
}
*** $left_rec = countRecords() - ($page * $rec_limit); ***
$total_records = countRecords(); // countRecords() should be self-explanatory
$total_pages = ceil($total_records / $rec_limit); // $rec_limit is 100
$adjacents = 2;
$previousPage = $page - 1;
$nextPage = $page + 1;
$querystring = "";
$start = ($page < $adjacents ? 1 : $page - $adjacents); // <-- i think the issue is here
$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"><ul class="pager"><li>First</li>";
if ($left_rec < $rec_limit)
{
$last = $page - 1;
echo #"<li>Previous</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>Previous</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 would really appreciate the help in removing page 0 from the application. Please disregard any typos or missing quotes. The code works with the exception of it showing page 0.
I added a picture of what the application showing page 0. It only shows page 0 when I go to page 2. After that, I no longer see page 0.
Please let me know what I have to do.
Thanks.
Some advice:
You really shouldn't suppress errors using #, instead you should be instantiating all of your variables and writing proper code.
Don't hard-code pagination into each page. Instead, wrap it in a reusable function.
Example:
// draws a menu for navigating multiple pages of content
function paginate($page, $display, $total) {
if(isset($_SERVER['QUERY_STRING']) && trim($_SERVER['QUERY_STRING']) != '') {
if(stristr($_SERVER['QUERY_STRING'], 'page=')) {
$query = '?' . preg_replace('/page=\d+/', 'page=', $_SERVER['QUERY_STRING']);
} else {
$query = '?' . $_SERVER['QUERY_STRING'] . '&page=';
}
} else {
$query = '?page=';
}
$pages = $total <= $display ? 1 : ceil($total / $display);
$self = htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'utf-8');
$first = 'first';
$prev = 'prev';
$next = 'next';
$last = 'last';
echo '<p>';
echo ($page > 1) ? "$first | $prev |" : 'first | prev |';
echo '(page ' . $page . ' of ' . $pages . ')';
echo ($page < $pages) ? "| $next | $last" : '| next | last';
echo '</p>';
}
// output example
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$display = 100;
$start = $display * $page - $display;
$total = countRecords($start, $display);
paginate($page, $display, $total);
I agree with #mister martin, but if you use this code fundamentally, try to change
$start = ($page < $adjacents ? 1 : $page - $adjacents);
To:
$start = ($page < $adjacents ? $page : $page - $adjacents);
Edited: maybe problem in undefined $left_rec, check demo. You can change $s like $_GET['page'] and as I see all works correctly.
Demo.
<?php
$rec_limit = 100;
$targetpage = "dispatch.php";
$total_records = countRecords();
// Nav part
$page = intval($_GET['page'])? $_GET['page']: 1;
$offset = $rec_limit * ($page - 1);
$total_pages = ceil($total_records / $rec_limit); // $rec_limit is 100
$adjacents = 2;
$previousPage = $page - 1;
$nextPage = $page + 1;
$start = ($page < $adjacents ? $page : $page - $adjacents); // <-- I think the issue is this line
$beginning = 1;
$end = ($page > $total_pages - $adjacents ? $total_pages : $page + $adjacents);
$uri = $_GET;
unset($uri['page']);
$querystring = http_build_query($uri);
echo '<div class="row-fluid"><div class="span2"><ul class="pager"><li>First</li>';
if($left_rec < $rec_limit && ($page > 1))
{
echo "<li>Previous</li>";
for($i= $start; $i <= $end; $i++)
{
echo "<li " . ((($page)==$i)? "class=\"active\"" : "") . ">$i</li>";
}
} else if ($page > 1)
{
echo "<li>Previous</li> ";
for($i= $start; $i <= $end; $i++)
{
echo "<li " . ((($page)==$i)? "class=\"active\"" : "") . ">$i</li>";
}
echo "<li>Next</li>";
} else {
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>';
?>

PHP remove page 0 from pagination

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);

PHP Pagination with 5 pages

if( isset($_GET['page'] ) )
{
$page = $_GET['page']-1;
$offset = $recLimit * $page;$page = $_GET['page']+1;
}
else
{
$page=2;
$offset = 0;
}
$phpself = $_SERVER['PHP_SELF'];
if( $totalPages <= $noofpages )
{
echo "Pages if less than or equal 5 : ";
for($i=1; $i <= $totalPages; $i++)
{
echo "$i |";
}
}
else
{
$i=1;
for($i; $i <= $totalPages; $i++)
{
echo "$i |";
}
}
?><table border="1" cellpadding="8"><tr> <th>ID</th><th>Name</th><th>Age</th><th>E-mail ID</th><th>Verified</th>
I'm goin to make a PHP pagination but i've some problem, in this i want to show 5 pages and 4 records per page. and if we click on next button then it shows the remaining page. And there are total 7 pages.
Since I couldn't really understand your code, here is something to get you started:
$items_per_page = 4;
/* Get the total number of records */
$result = mysqli_query("select count(*) as n from ...");
$row = mysqli_fetch_assoc($result);
$total_count = $row["n"];
/* Calculate the total number of pages */
$total_pages = ceil($total_count / $items_per_page);
/* Determine the current page */
$current_page = intval(#$_GET["page"]);
if(!$current_page || $current_page < 1) { $current_page = 1; }
if($current_page > $total_pages) { $current_page = $total_pages; }
/* Get the records for the current page */
$limit = $items_per_page;
$offset = ($current_page - 1) * $items_per_page;
$result = mysqli_query("select ... limit " . $offset . ", " . $limit);
To display the pagination links, use this:
for($i = 1; $i <= $total_pages; $i++)
{
if($i > 1) { print(" | "); }
if($current_page == $i) { print($i); }
else { print('' . $i . ''; }
}

Adding previous(back) and next buttons next to the page numbers PHP

I have two tiny little problems;
1 . I want to add a previous / next button into this code
2 . I want it to only show like max 10 links between previous and next. So if i have 50 numbers/links it will only show 10 of them and not 50 links on the page.
I have searched on the clo
The code works, only need that two options in it.
Can someone help me out? Thank you !
<?php
include 'includes/connection.php';
$per_page = 8;
$pages_query = mysql_query("SELECT COUNT(`id`) FROM `products`");
$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 `name` FROM `products` LIMIT $start, $per_page");
while ($query_row = mysql_fetch_assoc($query)) {
echo '<p>', $query_row['name'] ,'</p>';
}
if ($pages >= 1 && $page <= $pages) {
for ($x=1; $x<=$pages; $x++) {
//echo $x, ' ';
echo ($x == $page) ? '<strong>'.$x.'</strong> ' : ''.$x.' ';
}
}else{
header("location:index.php?page=1");
}
?>
First of all, you should, just for good practice, put an "exit;" after the header() call at the end. It doesn't make a difference in this particular script, but keep in mind that any code following a header("Location: ...") call WILL be executed before redirection.
Now to your question, try this (UPDATE: This code has been tested and works.)
<?php
include 'includes/connection.php';
$per_page = 8;
$pages_query = mysql_query("SELECT COUNT(`id`) FROM `products`");
$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 `name` FROM `products` LIMIT $start, $per_page");
while ($query_row = mysql_fetch_assoc($query))
{
echo '<p>' . $query_row['name'] . '</p>';
}
// If the requested page is less than 1 or more than the total number of pages
// redirect to the first page
if($pages < 1 || $page > $pages)
{
header('Location: ?page=1');
// end execution of the rest of this script
// it will restart execution after redirection
exit;
}
// If more than one page, show pagination links
if($pages > 1)
{
$html = array();
$html[] = '<strong>';
// if you're on a page greater than 1, show a previous link
$html[] = (($page > 1) ? 'Previous ' : '');
// First page link
$pageFirst = '1';
$html[] = (($page == 1) ? "</strong>{$pageFirst}<strong>" : $pageFirst);
if ($pages > 6)
{
$start_cnt = min(max(1, $page - (6 - 1)), $pages - 6);
$end_cnt = max(min($pages, $page + 4), 8);
$html[] = ($start_cnt > 1) ? '...' : ' ';
for ($i = $start_cnt + 1; $i < $end_cnt; $i++)
{
$html[] = ($i == $page) ? '</strong>' . $i . '<strong>' : '' . $i . '';
if ($i < $end_cnt - 1)
{
$html[] = ' ';
}
}
$html []= ($end_cnt < $pages) ? '...' : ' ';
}
else
{
$html[] = ' ';
for ($i = 2; $i < $pages; $i++)
{
$html[] = ($i == $page) ? '</strong>' . $i . '<strong>' : '' . $i . '';
if ($i < $pages)
{
$html[] = ' ';
}
}
}
// last page link
$pageLast = '' . $pages . '';
$html[] = (($page == $pages) ? "</strong>{$pageLast}<strong>" : $pageLast);
// Show next page link if you're on a page less than the total number of pages
$html[] = ($page < $pages) ? ' Next' : '';
// If you're not on the last page, show a next link
$html[] = '</strong>';
}
else
{
// show page number 1, no link.
$html[] = '<strong>1</strong>';
}
echo implode('', $html);
Also note that the final ?> is not required in PHP files that do not have HTML code following the PHP code, so I left it off.
Buddy refer this URL
http://www.codediesel.com/php/simple-pagination-in-php/
OR
http://www.phpfreaks.com/tutorial/basic-pagination
Surely will help you.
Thanks

Categories