show page numbering in PHP - php

I am using this coed in PHP to show next and previous buttons for records in a mysql database:
$sql="SELECT * from customer";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$MaxRowsPerPage = 25;
$total_records = mysql_num_rows($rs);
$total_pages = ceil($total_records / $MaxRowsPerPage);
if(isset($_GET["page"])) {
$page = $_GET["page"];
} else {
$page=1;
}
$start_from = ($page-1) * $MaxRowsPerPage;
$sql.=" LIMIT $start_from, $MaxRowsPerPage";
I am echoing $total_records to show the total amount, how can i show the number from and to on the current page. for example, on page 1 it will be showing records 1 to 25 (because max rows per page is 25) and then page 2 will be showing records 26 to 50 and so on...

There a are many ways of doing this, but here's a simple pagination example I made. It will also show 1-25, 26-50 etc. It's heavily commented so it should be easy to understand.
<?php
// Connect to database
include 'includes/db_connect.php';
// Find total number of rows in table
$result = mysql_query("SELECT COUNT(*) FROM example_table");
$row = mysql_fetch_array($result);
$total_rows = $row[0];
// Set rows per page
$rows_per_page = 25;
// Calculate total number of pages
$total_pages = ceil($total_rows / $rows_per_page);
// Get current page
$current_page = (isset($_GET['p']) && $_GET['p'] > 0) ? (int) $_GET['p'] : 1;
// If current page is greater than last page, set it to last.
if ($current_page > $total_pages)
$current_page = $total_pages;
// Set starting post
$offset = ($current_page - 1) * $rows_per_page;
// Get rows from database
$result = mysql_query("SELECT * FROM example_table LIMIT $offset, $rows_per_page");
// Print rows
echo '<hr>';
while($row = mysql_fetch_array($result))
{
echo $row['id'].'<br />';
echo $row['text'];
echo '<hr>';
}
// Build navigation
// Range of pages on each side of current page in navigation
$range = 4;
// Create navigation link for previous and first page.
if ($current_page > 1)
{
$back = $current_page - 1;
echo ' PREV ';
if ($current_page > ($range + 1))
echo ' 1... ';
}
else
echo ' PREV ';
// Create page links, based on chosen range.
for ($i = $current_page - $range; $i < ($current_page + $range) + 1; $i++)
{
if ($i > 0 && $i <= $total_pages)
if ($i == $current_page)
echo ' [<strong>'.$i.'</strong>] ';
else
echo ' '.$i.' ';
}
// Create navigation link for next and last page.
if ($current_page != $total_pages)
{
$next = $current_page + 1;
if (($current_page + $range) < $total_pages)
echo ' ...'.$total_pages.' ';
echo ' NEXT ';
}
else
echo ' NEXT ';
?>

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
}

How to continue numbered list in all next pages with pagination?

I am trying to display data in an ordered list with pagination in php. It is working fine on page one but on next page, the list starts again from 1 instead of continuing from previous number.
Here is my code:
<?php
// find out how many rows are in the table
$sql01 = mysql_query("SELECT COUNT(*) FROM pm,pm_reply");
$r = mysql_fetch_row($sql01);
$numrows = $r[0];
$rowsperpage = 3;
$totalpages = ceil($numrows / $rowsperpage);
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
}
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
}
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
}
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
// while there are rows to be fetched...
$sql=mysql_query("select *from pm where send_to='$_GET[name]' limit $offset, $rowsperpage");
$sql2=mysql_query("select *from pm_reply where send_to='$_GET[name]' limit $offset, $rowsperpage");
echo "<ol>";
while($rows=mysql_fetch_assoc($sql)) {
echo"<li>From: <a href='profile.php?name=$rows[send_by]'>$rows[send_by]</a><br><br><a style='text-decoration:none; font-size:14pt;' href='view_pm.php?name=$_GET[name]&pm=$rows[subject]'>$rows[subject]</a></li>";
echo "<hr>";
echo "<br>";
}
while($rows2=mysql_fetch_assoc($sql2)) {
echo"<li>From: <a href='profile.php?name=$rows2[replied_by]'>$rows2[replied_by]</a><br><br><a style='text-decoration:none; font-size:14pt;' href='view_pm.php?name=$_GET[name]&pm=$rows2[subject]'>$rows2[subject]</a></li>";
echo "<hr>";
echo "<br>";
}
echo "</ol>";
echo "</div>";
//End Div Content
echo "<div style='clear:both;'></div>";
echo "<br>";
echo "<br>";
echo "<br>";
echo "<div id='pagelinks'>";
/****** 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']}?name=$_GET[name]&currentpage=1'>First...</a> ";
// get previous page num
$prevpage = $currentpage - 1;
}
// 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 ($x == $currentpage) {
// if we're on current page...
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
} else {
// if not current page...
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?name=$_GET[name]&currentpage=$x'>$x</a> ";
}
}
}
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
echo " <a href='{$_SERVER['PHP_SELF']}?name=$_GET[name]&currentpage=$totalpages'>...Last</a> ";
}
Just add start="$offset" to your echo "<ol>"; line.
echo "<ol start='$offset'>";

PHP pagination, only count rows from where column is not empty

I'm using the following code to show some pages of data, but now i don't want to display empty pages whereas the data is somewhere in page 12 while page 1 is empty.
So the problem seems to be in this block of code.
//$sql = "SELECT COUNT(*) FROM ads";
$sql = "SELECT COUNT(*) FROM ads WHERE position IS NOT NULL or position != ''";
$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 = 20;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
and here's the full code.
$sql = "SELECT COUNT(*) FROM ads WHERE position IS NOT NULL or position != ''";
$result = mysql_query($sql, $con) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
$rowsperpage = 20;
$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 ads LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $con) or trigger_error("SQL", E_USER_ERROR);
//require 'carrer_ad.php';
// while there are rows to be fetched...
while ($row = mysql_fetch_assoc($result)) {
// echo data
//echo $list['name'] . "<br />";
require 'carrer_ad.php';
$adCondition = (!empty($row['position'])) ? $ad : '';
echo $adCondition;
} // 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> ";
}
try changing your query to:
$sql = "SELECT COUNT(*) FROM ads WHERE position IS NOT NULL and position <> ''";
Try this
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

Pagination system always missing 1 result

I have a pagination system, that fetches all of the results from a database & then loads them into a pagination.
Let's say I set the limit to 5 results per page, it will generate more pages, and order the results by date & time.
But I have a problem, my system always missing the most new result (by date/time) in the database, I have no idea why..
This is the code:
// how many rows to show per page
$rowsPerPage = 10;
// by default we show first page
$page_num = 1;
// if $_GET['page'] defined, use it as page number, $_GET gets the page number out of the url
//set by the $page_pagination below
if(isset($_GET['page'])){$page_num = $_GET['page'];}
//the point to start for the limit query
$offset = $page_num;
// Zero is an incorrect page, so switch the zero with 1, mainly because it will cause an error with the SQL
if($page_num == 0) {$page_num = 1;}
// counting the offset
$sql = "SELECT * FROM comments ORDER BY date, time desc LIMIT $offset, $rowsPerPage";
$res = $pdo->query($sql);
// how many rows we have in database
$sql2 = "SELECT COUNT(comment_id) AS numrows FROM comments";
$res2 = $pdo->query($sql2);
$row2 = $res2->fetch();
$numrows = $row2['numrows'];
// print the random numbers
while($row = $res->fetch())
{
//Echo out your table contents here.
echo $row[1].'<BR>';
echo $row[2].'<BR>';
echo '<BR>';
}
// how many pages we have when using paging?
$numofpages = ceil($numrows/$rowsPerPage);
// print the link to access each page
$self = "events.php?";
$page_pagination = '';
if ($numofpages > '1' ) {
$range = 10; //set this to what ever range you want to show in the pagination link
$range_min = ($range % 2 == 0) ? ($range / 2) - 1 : ($range - 1) / 2;
$range_max = ($range % 2 == 0) ? $range_min + 1 : $range_min;
$page_min = $page_num- $range_min;
$page_max = $page_num+ $range_max;
$page_min = ($page_min < 1) ? 1 : $page_min;
$page_max = ($page_max < ($page_min + $range - 1)) ? $page_min + $range - 1 : $page_max;
if ($page_max > $numofpages) {
$page_min = ($page_min > 1) ? $numofpages - $range + 1 : 1;
$page_max = $numofpages;
}
$page_min = ($page_min < 1) ? 1 : $page_min;
if ( ($page_num > ($range - $range_min)) && ($numofpages > $range) ) {
$page_pagination .= '<a class="num" title="First" href="'.$self.'page=1"><</a> ';
}
if ($page_num != 1) {
$page_pagination .= '<a class="num" href="'.$self.'page='.($page_num-1). '">Previous</a> ';
}
for ($i = $page_min;$i <= $page_max;$i++) {
if ($i == $page_num)
$page_pagination .= '<span class="num"><strong>' . $i . '</strong></span> ';
else
$page_pagination.= '<a class="num" href="'.$self.'page='.$i. '">'.$i.'</a> ';
}
if ($page_num < $numofpages) {
$page_pagination.= ' <a class="num" href="'.$self.'page='.($page_num + 1) . '">Next</a>';
}
if (($page_num< ($numofpages - $range_max)) && ($numofpages > $range)) {
$page_pagination .= ' <a class="num" title="Last" href="'.$self.'page='.$numofpages. '">></a> ';
}
}
echo $page_pagination.'<BR><BR>';
echo 'Number of results - '.$numrows ;
echo ' and Number of pages - '.$numofpages.'<BR><BR>';
$res2->closeCursor();
Question:
What have I done wrong? I cant' really see anything wrong, but I always get this error:
Notice: Undefined variable: page_pagination
Line:
echo $page_pagination.'<BR><BR>';
It always happens on a different line, depends on the results amount, but to fix that I need to declare page_pagination = ''; before the whole thing.
How can I fix this and what is causing this problem?
Thanks.
Your $offset is being set to 1. The newest one is always missing because it's going form 1-10 rather than 0-9. Index starts at 0. The following should work.
$offset = ($rowsPerPage * $page_num) - $rowsPerPage;

Using a count ++ function with pagination

The HTML table below is paginated. On page one, $count++ starts at one and then goes up, which is what I want.
The problem is that when I click on page two, $count++ starts at one again.
How can I make it start at 101 on page two?
$presult = mysql_query("SELECT COUNT(*) FROM login") or die(mysql_error());
$rr = mysql_fetch_row($presult);
$numrows = $rr[0];
$rowsperpage = 100;
$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;
$tzFrom3 = new DateTimeZone('America/New_York');
$tzTo3 = new DateTimeZone('America/Phoenix');
$sqlStr3 = "SELECT
loginid,
username,
created,
activated
FROM login
WHERE activated = 1
ORDER BY created ASC
LIMIT $offset, $rowsperpage";
$result = mysql_query($sqlStr3);
$arr = array();
echo "<table>";
while ($row = mysql_fetch_array($result)) {
$dt3 = new DateTime($row["created"], $tzFrom3);
$dt3->setTimezone($tzTo3);
echo '<tr class="backgroundnonttsu">';
echo '<td>'.$count++.'</td>';
echo '<td >'.stripslashes($row["username"]).'</a></td>';
echo '<td >'.$dt3->format('F j, Y').'</td>';
echo '</tr>';
}
echo "</table>";
$range = 3;
/****** build the pagination links ******/
// range of num links to show
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <div class='pages'><a href='http://www.domain.com/directory/file.php?currentpage=1' class='links'><<</a></div> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <div class='pages'><a href='http://www.domain.com/directory/file.php?currentpage=$prevpage' class='links'><</a></div> ";
} // 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 " <div class='pages'>[<b>$x</b>] </div>";
// if not current page...
} else {
// make it a link
echo " <div class='pages'><a href='http://www.domain.com/directory/file.php?currentpage=$x' class='links'>$x</a></div> ";
} // 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 " <div class='pages'><a href='http://www.domain.com/directory/file.php?currentpage=$nextpage' class='links'>></a></div> ";
// echo forward link for lastpage
//echo " <div class='pages'><a href='http://www.domain.com/directory/file.php?currentpage=$totalpages' class='links'>>></a></div> ";
} // end if
/****** end build pagination links ******/
if($currentpage==1){
$count=1;
}else{
$count =1+($currentpage*$rowsperpage);
}
Just do
$count = $offset + 1
right after you set offset. You only need one line of code.

Categories