Pagination with PHP and MySQL - php

I've tried a load of different code snippets that are out there for using pagination in my result set. I've got the same problem in each case. Using LIMIT on the end of the query I can display the first page correctly along with the navigation links for the correct number of pages (so the code doing the calculations with number of rows returned and number to display on each page is right), but when you click to follow the link to any of the other pages then they're blank. So how do I get the updated query to run again and display my results on the subsequent pages?
This is one piece of code that I've tried:
$rowsperpage = 10;
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) { $currentpage = (int) $_GET['currentpage']; }
else { $currentpage = 1; }
// if current page is greater than total pages...
if ($currentpage > $totalpages) { $currentpage = $totalpages; }
// if current page is less than first page...
if ($currentpage < 1) { $currentpage = 1; }
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// run the query
$sql = "SELECT * FROM table WHERE keyword LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $link) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result))
{
//echo data for each record here
}
// building pagination links
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if
Not permitted to show rest of navigation code due to too many hrefs, but the links appear correctly. The problem seems to be how the query is carried over to the next page.

You have to use limit offset, rowcount.
Typically for nth page
offset= (n-1)*pagesize and rowcount=pagesize

Related

pagination with dots in middle generate with PHP

Im trying to create pagination using PHP but I have issue with quantity of page.
my pagination created used
foreach(range(1, $pager) as $i){
echo '<span class="pagination-num" data-pager="'.$i.'">'.$i.'</span>';
}
the problem comes when the range is too large. like on the image below. variable $pager contains a dynamic value. $pager counts how many pages should created from quantity of the content.
I set 10 content per page, so if there is 100 content:
$pager = ceil($content / 10);
it's there any way to edit pagination with dots. (next and prev I created using custom Jquery).
first of all you need to set items per page for example 10 items per page
<?php
$ipp = 10; //Item Per Page
if(isset($_GET["page"]) AND $_GET["page"] > 0){
$page_number = $_GET['page']; // page number
}
else{$page_number = 1;}
$total_items = 100; //total items
$total_pages = ceil($total_items/$ipp); //total pages
$page_position = (($page_number-1) * $ipp); //page position
?>
just in case if you are using sql:
"SELECT * FROM `table` WHERE --something-- ORDER BY `id` ASC LIMIT {$page_position}, {$ipp}"

php pagination : page 2 shows same page 1 rows if new data added

i'm trying to make my own pagination system ignores the new data if someone trying to open the next page:
example:
i have this table :
1. apple
2. orange
3. banana
4. burger
5. pizza
6. spaghetti
and i only show 3 rows for each page.
mysql query:
// $page = 0 for first page
$sql = "SELECT * FROM mytable ORDER BY id DESC LIMIT $page, 3";
the result is like this
page #1 :
6. spaghetti
5. pizza
4. burger
page #2 :
3. banana
2. orange
1. apple
let's say right now I'm in page #1 and someone else added 3 new rows:
water
juice
coffee
what will happen now is if i go to page #2 i will get a repeated page !
now page #2 is gonna be :
6. spaghetti
5. pizza
4. burger
the reason of that is because page #1 is showing the new data:
9. water
8. juice
7. coffee
how can i stop this to happen if the user didn't refresh the first page and only wanted to view the second page ?
it's a problem especially if you're trying to make your pagination looks just like twitter!
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM mytable";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql = "SELECT * FROM mytable ORDER BY id DESC LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
// echo data
echo $list['id'] . " : " . $list['number'] . "<br />";
} // end while
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?>
You can use something like this to get proper pagination for your table items. You can remove ORDER BY & DESC to know how the sql query result changes.
$page; // $page is current page
$result = 3; // As you need 3 results per page.
$offset = ($page * $result) - $result;
$sql = "SELECT * FROM mytable ORDER BY id DESC LIMIT $result OFFSET $offset";
i had to use session to make it work as i want it , and here's how i solved it:
$count = $PDO->query("SELECT id FROM mytable")->rowCount(); //count rows
if(!isset($_SESSION['rowCount']))
{
$_SESSION['rowCount'] = $count; // save row counts
}
if(isset($_GET['page']))
{
$offset = ($_GET['page'] -1) * 3 + $count - $_SESSION['rowCount'];
}
else
$offset = 0;
$sql = $PDO->prepare("SELECT * FROM mytable ORDER BY id DESC LIMIT $offset, 3");
$sql->execute();
also i unset the session when user comes back to page 1.

php my sql pagination help need for links and advancing the next offset

hi i'm trying to paginate a php mysql database, and I can't figure out what make the results move to the next page, it's stuck at record row zero and what do i change to make it go to the next set of results? is this the offset hooked to the nav link somehow does it have to recall a mysql query? how does this work?
//pagination
//find out how many rows are in the table
$sql = "SELECT * FROM hotels_database";
$result = mysql_query($sql, $con) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 2;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = preg_replace('#[^0-9]#i','', $_GET['currentpage']);
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql = "SELECT * FROM hotels_database LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $con) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
// echo data
for ($stars=1;$stars<=floor($list['stars']);$stars++){
$star_string .= "<img src='images/star.jpg'/>";
}
if (($list['stars']-floor($list['stars']))> 0){
$star_string .= "<img src='images/half_star.jpg'/>";
}
$hotels_database .= "<div style='display:table-row;height:70px;'><div style='width:60px;height:60px;display:table-cell;float:left;'><img src='".$list['pic']."' width='60px'/></div>"."<div style='width:280px;display:table-cell;vertical-align:top;text-align:left;padding-left:5px;font-size:12px;'><a href='#' class='database_link'>".$list['hotel']."</a>".$star_string."<br/><span style='font-size:10px;'>".$list['addy']."</span><br/>Guest score: <span style='color:red;font-size:14px;'>".$list['score']."</span> out of 10"."<br/>"."<li class='database_arrow'>Display Amenities & More Info</li>"."</div>"."<div style='width:78px;height:60px;display:table-cell;vertical-align:top;'><span style='font-family:arial;color:green;font-size:15px;'>$".$list['price']."</span><br/>per night<div style='border-radius:10px;background-color:#1284d3;height:25px;width:70px;left:10px;top:10px;position:relative;border:1px black solid;color:white;font-family:arial;line-height:8px;'><br/>select</div><br/></div>"."</div><hr style='color:#c8ff78;'/>";
$star_string="";
} // end while
/****** build the pagination links ******/
// range of num links to show
//pagination
/*
ya, so i can't figure out how to go to the next offset what href do i use in this case? and why isn't the currentpage query string being displayed in my addy bar? please take a look,
As D.N said code would be helpful but in general it goes
if(isset($_GET['offset']) {
$offset = $_get['offset'];
}
else{
$offset = 0;
}
then in the SQL call you add:
'what ever the call is' "limit $limit offset $offset"

How to finalize pagination implementation

Thanks to tons of great help by some of you one here, I've finally been successful in my first pagination project...well almost.
My script works wonderfully except one tiny hitch. There are 40 "rows' page. When there are no more "rows" to display, the pagination continues to paginate blank pages.
To be more specific. page 13 is the last page with rows on it, but you can still hit next and go onto blank pages.
The solution is obvious - to have the "next" button disappear if there are no rows left, but for some reason all of the if statements I've tried are failing to do so.
Here is the query:
$rowsperpage = 40; // THERE ARE 40 AIRWAVES PER PAGE
$currentpage = (int)$_GET['currentpage']; // This is getting which "page" the user wants to see, and putting it in $currentpage
if ($currentpage > 0) { // If $currentpage is greater than 0, we'll need to compensate by subtracting 1, so that we pull the correct set of results. Otherwise, we'll just start at 0 (see the else)
$offset = ($currentpage - 1) * $rowsperpage;
}
else {
$offset = 0;
}
$query = "SELECT * FROM `CysticAirwaves` WHERE `FromUserID` = `ToUserID` AND `status` = 'active' ORDER BY `date` DESC, `time` DESC LIMIT $offset, $rowsperpage";
$request = mysql_query($query, $connection);
$counter = 0;
while ($result = mysql_fetch_array($request)) {
and here is the pagination links:
// find out how many rows are in the table
$query = "SELECT COUNT(*) FROM `CysticAirwaves`";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 40;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int)$_GET['currentpage'];
}
else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage + 1) * $rowsperpage;
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
// echo data
echo $list['id'] . " : " . $list['number'] . "<br />";
} // end while
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
$prevpage = $currentpage - 1;
echo "<div id='all_page_turn'>
<ul>
<li class='PreviousPageBlog round_10px'>
<a href='http://www.cysticlife.org/Airwave_build.php?currentpage=$prevpage'>Previous</a>
</li>
<ul>
</div>";
} // end if
// if not on last page, show forward and last page links
if ($currentpage != $totalpages)) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <div id='all_page_turn'>
<ul>
<li class='PreviousPageBlog round_10px'>
<a href='http://www.cysticlife.org/Airwave_build.php?currentpage=$nextpage'>Next</a>
</li>
</ul>
</div> ";
}
Thanks in advance
Change your
if ($currentpage != $totalpages)) {
to
if ($currentpage < $totalpages) {
For one, there's an extra parenthesesisesis, and you should never rely on exact matching an upper threshold.
Edit:
I think I see the problem. You need to use the same WHERE clause as in your actual select query when doing your COUNT:
$query = "SELECT COUNT(*) FROM `CysticAirwaves` " .
"WHERE `FromUserID` = `ToUserID` AND `status` = 'active'";
Otherwise, you're getting the count of all rows in the table, even ones you're not displaying.

Pagination Help

*EDIT***
I've made great progress by combining the main query that pulls the airwaves with some variables from the pagination query and have finally gotten the pagination to work. The only problem now is that the first page is blank and page two is correct starting with result 41-80
Here is the query that limits and pulls the airwaves
$rowsperpage = 40;
$currentpage = (int) $_GET['currentpage'];
$offset = ($currentpage - 1) * $rowsperpage;
$query = "SELECT * FROM `CysticAirwaves` WHERE `FromUserID` = `ToUserID` AND `status` = 'active' ORDER BY `date` DESC, `time` DESC LIMIT $offset, $rowsperpage" ;
$request = mysql_query($query,$connection);
$counter = 0;
while($result = mysql_fetch_array($request)) {
and here is the pagination code:
$query = "SELECT COUNT(*) FROM `CysticAirwaves`";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 40;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$query2 = "SELECT `id` FROM `CysticAirwaves` LIMIT $offset, $rowsperpage";
$result = mysql_query($query2, $connection) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
// echo data
echo $list['id'] . " : " . $list['number'] . "<br />";
} // end while
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='http://www.cysticlife.org/Airwave_build.php?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='http://www.cysticlife.org/Airwave_build.php?currentpage=$prevpage'><</a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='http://www.cysticlife.org/Airwave_build.php?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='http://www.cysticlife.org/Airwave_build.php?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='http://www.cysticlife.org/Airwave_build.php?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?>
So long story short, I just am not able to pull the first 40 results but after that its fine
This is a better way to go about pagination:
SELECT SQL_CALC_FOUND_ROWS id FROM `CysticAirwaves` LIMIT $offset, $rowsperpage
Select the data you want to display using the example query above which will return the same result as your query2
Then execute another SQL query:
SELECT FOUND_ROWS()
This will return the number of rows found without using a limit. See more here:
http://dev.mysql.com/doc/refman/5.0/en/limit-optimization.html
This would be the fastest way to manage pagination.
You would then loop through the results of your first query and display then. All you need to keep track of is what page you are on, and how many rows to show per page.
If you page number * $rowsperpage > the result of the second select (FOUND_ROWS) then you do not need to calculate or show the 'next' pages options/links.
For 'next' pages, loop 3 times incrementing the page number or next page * $rowsperpage > total rows.
For 'previous' pages, loop 3 times decrementing the page number or previous page = 1 (break out of loop in this case).
That should do the trick.
Probably you code so much, that it's hard to read what you've once written. You seem to put a comment next to each line of code, which might underline that. So you probably should reduce the code to reduce this problem.
This is just a suggestion, you wrote:
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
All these if clauses you need to deal with! All these comments to read! Isn't that a burden?
// currentpage must be within 1 and total of pages.
$currentpage = max(1,min($totalpages, $currentpage));
How about that? If you have problems to understand it, you can put some comments on top that explain it as you do as well in your code - in your words if mine are not fitting, it's just a suggestion.

Categories