PHP Pagination with 5 pages - php

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 . ''; }
}

Related

php pagination on second page not working

$dwdb=mysqli_connect("localhost","root","","dw");
//this is my page number
$page=(isset($_GET['page']) && $_GET['page']>0)?$_GET['page']:1 ;
//this is my cat_id
$new=(isset($_GET['year']) && $_GET['year']>0)?$_GET['year']:1 ;
$perpage=2;
$limit=($page > 1)?($page*$perpage)-$perpage:0;
$query=mysqli_query($dwdb,"select *from movies where y_id='$new' limit {$limit},{$perpage}");
while($result=mysqli_fetch_array($query)){
$id=$result['m_id'];
$name=$result['title'];
$img=$result['image'];
echo"<div><a href='downloadpage.php?yc=$id'>$id.....$name<br><img src='i/image/$img' style='height:200px;width:200px;'/></a></div>";
}
$query1=mysqli_query($dwdb,"select *from movies where y_id='$new'");
$total=mysqli_num_rows($query1);
$pages=ceil($total/$perpage);
echo "<a href='index1.php?page=1'>".'First Page'."</a>";
for ($i=1; $i<=$pages;$i++){
echo "<a href='index1.php?page=".$i."'>".$i."</a> ";
};
echo "<a href='index1.php?page=$pages'>Last page</a>";
That is my code. The problem is that on my second page i have result of first $new variable .......................................................................................................................................................................
... i have a problem that on my second page i have result of first $new variable
That's because you're not including $new variable in the pagination links. So every time you go to 2nd, 3rd, 4th, ... page, you'll get the same $new value as 1, and that's because of this statement,
$new=(isset($_GET['year']) && $_GET['year']>0)?$_GET['year']:1 ;
Include this variable in the pagination links so that you could get it's value in the subsequent pages. So your pagination links section would be like this:
// your code
echo "<a href='index1.php?page=1&year=".$new."'>".'First Page'."</a>";
for ($i=1; $i<=$pages;$i++){
echo "<a href='index1.php?page=".$i."&year=".$new."'>".$i."</a> ";
}
echo "<a href='index1.php?page=".$pages."&year=".$new."'>Last page</a>";
for pagination use this code in file with name: view-paginated.php
$per_page = 10;
$result = mysql_query("SELECT * FROM table");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
$start = 0;
$end = $per_page;
}
}
else
{
$start = 0;
$end = $per_page;
}
echo "<p><a href='view.php'>show all</a> | <b>page:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='view-paginated.php?page=$i'>$i</a> ";
}
for ($i = $start; $i < $end; $i++)
{
if ($i == $total_results) { break; }
echo mysql_result($result, $i, 'YOUR COLUMN') ;
}

show page numbering in 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 ';
?>

PHP pagination Adjacents

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

pagination of search result is not working

Pagination problem in search result
I am trying to paginate the search results, Here is the code that i'm using to look up for the search queries from user's form. I am getting search results paginated, but when i click 2 nd page of results it shows undefined index for those item posted...While gone through tutorials i have seen to use $_GET instead of $_POST ,after doing that chane also no improvement in results
As i am new to this php code, can you guys help or guide me in the right direction?
/////////////test.php//////////////////
mysqli_report(MYSQLI_REPORT_ERROR);
// number of results to show per page
$per_page = 2;
// figure out the total pages in the database
if ($result = $mysqli->query("SELECT * FROM bridegroom where Gender like '%$Name%' and Castest like'%$caste%' and Location like '%$location%' order by AGE"))
{
if ($result->num_rows != 0){
$total_results = $result->num_rows;
// ceil() returns the next highest integer value by rounding up value if necessary
$total_pages = ceil($total_results / $per_page);
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
$start = 0;
$end = $per_page;
}
}
else
{
$start = 0;
$end = $per_page;
}
// display pagination
echo "<p> <b>View search results:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
if (isset($_GET['page']) && $_GET['page'] == $i)
{
echo $i . " ";
}
else
{
echo "<a href='test.php?page=$i'>$i</a> ";
}
}
echo "</p>";
// display data in table
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// find specific row
$result->data_seek($i);
$row = $result->fetch_row();
// echo out the contents of each row into a table
echo ("Name:$row[1]<br><span class=\"old\"> Age:$row[4]</span><br><span class=\"sold\">Caste:$row[5]</span><br><span class=\"old\">Location:</span><span class=\"sold\">$row[6]</span><br><br>");
}
// close table>
}
else
{
echo "No results to display!";
}
}
// error with the query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
// display pagination
echo "<p> <b>Your search results:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
if (isset($_GET['page']) && $_GET['page'] == $i)
{
echo $i . " ";
}
else
{
echo "<a href='test.php?page=$i'>$i</a> ";
}
}
echo "</p>";
?>

php pagination numbered page links

This is a pagination code used for the navigation, any ideas how to get this code to display simply a numbered list of the pages as links?
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
}
else {
$pageno = 1;
}
if(isset($_GET['niche']))
{
$query = "SELECT count(*) FROM studies WHERE niche = '{$_GET['niche']}'";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
}
$query_data = mysql_fetch_row($result);
$numrows = $query_data[0];
$rows_per_page = 4;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
}
if ($pageno < 1) {
$pageno = 1;
} // if
$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$query = "SELECT * FROM studies WHERE niche = '{$_GET['niche']}' $limit";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
and...
if ($pageno == 1) {
echo "<div class='container'>FIRST PREV ";
} else {
echo "<div class='container'> <a href='{$_SERVER['PHP_SELF']}?pageno=1&niche={$_GET['niche']}'>FIRST</a> ";
$prevpage = $pageno-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$prevpage&niche={$_GET['niche']}'>PREV</a> ";
} // if
echo " ( Page $pageno of $lastpage ) ";
if ($pageno == $lastpage) {
echo " NEXT LAST</div><br />";
} else {
$nextpage = $pageno+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$nextpage&niche={$_GET['niche']}'>NEXT</a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$lastpage&niche={$_GET['niche']}'>LAST</a></div><br /> ";
} // if
?>
Try this:
$totalpages = ceil($numrows / $rows_per_page);
if($totalpages >= 1){ $pagelinkcount = 1; } else { $pagelinkcount = 0; }
while($pagelinkcount <= $totalpages && $totalpages > 1) {
echo "{$pagelinkcount} ";
$pagelinkcount++;
}
On a side note, as Ian Elliot pointed out in the comments for your question, using $_GET in an SQL query leaves your database VERY vulnerable, and is thus considered an extremely insecure coding practice. You should escape and parse the $_GET data that you need diligently before passing it to the DB.
Here's a function I've been using for pagination for a while. It returns nothing if there's only one page, returns up to 15 pages with numbers, then adds a dropdown that lets you skip to any 10th page when there are more than 15 pages. It relies on some prev/next images, but you can easily take that out.
function paginate( $items_per_page, $number_of_results ) {
if( isset( $_REQUEST['page'] ) ) {
$page = $_REQUEST['page'];
} else {
$page = 1;
}
$url = htmlentities( preg_replace( '/(\?|&)page=[\d]+/', '', $_SERVER['REQUEST_URI'] ).'&' );
$html = '';
$numbers_html = '';
$navigation_html = '';
if( $number_of_results > $items_per_page ) {
$html .= '<div class="pagination">';
if( $page == 1 or $page == '1' ) {
$numbers_html .= '<img src="images/prev.png" alt="← prev" class="inactive" /> - ';
} else {
$numbers_html .= '<img src="images/prev.png" alt="← prev" /> - ';
}
$count = 0;
$total_pages = ceil( $number_of_results / $items_per_page )-1;
while( $count <= $total_pages ) {
$count++;
if( $total_pages > 12 and floor($count / 10) != floor($page / 10) ) {
while( $count < $total_pages and floor($count / 10) != floor($page / 10) ) {
if( $count == 1 ) {
$endpage = 9;
} elseif( $count + 9 < $total_pages ) {
$endpage = $count + 9;
} else {
$endpage = $total_pages + 1;
}
$ten_group = floor( $count / 10 );
if( $ten_group == 0 ) {
$navigation_html .= '<option value="'.$url.'page='.$count.'">page 1</option>';
} else {
$navigation_html .= '<option value="'.$url.'page='.$count.'">page '.($ten_group*10).'</option>';
}
$count += 10;
}
$count -= 2;
} else {
if( $page == $count ) {
$numbers_html .= '<span class="current">'.$count.'</span>';
if( $count == 1 ) {
$endpage = 9;
} elseif( $count + 9 < $total_pages ) {
$endpage = $count + 9;
} else {
$endpage = $total_pages + 1;
}
if( $total_pages > 15 ) {
$ten_group = floor( $count / 10 );
if( $ten_group == 0 ) {
$navigation_html .= '<option value="'.$url.'page='.$count.'" selected="selected">page 1</option>';
} else {
$navigation_html .= '<option value="'.$url.'page='.$count.'" selected="selected">page '.($ten_group*10).'</option>';
}
}
} else {
$numbers_html .= ''.$count.'';
}
if( ( $total_pages > 12 and $count % 10 == 9 ) or $count == $total_pages+1 ) {
} else {
$numbers_html .= ' - ';
}
}
}
if( $page != $count ) {
$numbers_html .= ' - <img src="images/next.png" alt="next →" />';
} else {
$numbers_html .= ' - <img src="images/next.png" alt="next →" class="inactive"/>';
}
$count++;
$html .= '<div class="pagination_numbers">'.$numbers_html.'</div>';
if( $navigation_html ) {
$html .= '<div class="pagination_navigation">skip to: <select onchange="window.location=this.value">'.$navigation_html.'</select> of '.($total_pages+1).'</div>';
}
$html .= '</div>';
}
return $html;
}
If you have many pages to display, you might want to consider "logarithmic" page naviagtion, as I describe in my answer here:
How to do page navigation for many, many pages? Logarithmic page navigation
(Sample PHP code only handles the pagination display - not the DB query).

Categories