How to make pagination in PHP, mysql - php

I wonder how to make pagination in PHP
May I ask you a favor of you?
This code have not error.
But I do not know what $current_page make
<?php
$con = mysqli_connect("localhost", "root", "", "dbdb") or die("error");
$page_size = 10;
$page_list_size = 10;
if (isset($_POST['search'])) {
$valueTosearch = $_POST['valueTosearch'];
$query = "SELECT * FROM `shipment` WHERE CONCAT(`Ship_Date`,`Model_No`,`Serial_No`)LIKE'%" . $valueTosearch . "%' ORDER BY Ship_Date DESC LIMIT $page_size";
$search_result = filterTable($query);
} else {
$query = "SELECT * FROM `shipment` ORDER BY Ship_Date DESC LIMIT $page_size";
$search_result = filterTable($query);
}
function filterTable($query) {
$con = mysqli_connect("localhost", "root", "", "dbdb");
$filter_Result = mysqli_query($con, $query);
return $filter_Result;
}
echo "<center><h1>info</h1></center> <br><br>";
$ret = mysqli_query($con, $query);
if ($ret) {
echo mysqli_num_rows($ret), " <br><br>";
$count = mysqli_num_rows($ret);
} else {
echo "error :" . mysqli_error($con);
exit();
}
$query = "SELECT count(*) FROM shipment";
$result_count = mysqli_query($con, $query);
$result_row = mysqli_fetch_array($result_count);
$total_row = $result_row[0];
if ($total_row <= 0)
$total_row = 0;
$total_page = ceil($total_row / $page_size);
$current_page = ceil();
?>
I wonder how to make pagination in PHP
May I ask you a favor of you?
This code have not error.
But I do not know what $current_page make

I think you have a mistake on the mysql query, limitting to $page_size you will get only a number of results = $page_size, but you will always get the $page-size 1st elements, if you want to page results you need to add offset.
This way first page will be $page_size elements with offset 0, second page $page_size elements with $page_size offset, and in general the nth page will be $page_size elements with (n-1) times $page_size offset.
In the last line you are missing an argument:
$current_page = ceil(); should be $current_page = ceil($lowest_element_in_result_set/$page_size);

$current_page should be the number of the page user want to view and this would be a input from user.
this is my implementation.
hope this will help you .
$pagenum = $_GET['pagenum'];//get the page number user want to view
$con = mysqli_connect("localhost", "root", "9272", "new_platform_7");
$query = 'select * from table1';
$filter_Result = mysqli_query($con, $query);//execute query without limit to get total number of rows
$rows = mysqli_num_rows($filter_Result);//total number of rows
if (!(isset($pagenum)))
{
$pagenum = 1;//if user hasn't give page number set page to page number 1
}
$page_rows = 30;//the page size (number of rows in each page)
$last = ceil($rows/$page_rows);//total number of pages //use ceil to avoid fractions
if ($pagenum < 1){ //if user give negative page number. set page number to 1
$pagenum = 1; //this will happen if user clicked the Previous page link when current page is 1
}elseif ($pagenum > $last) //if page number is greater than calculated number of pages . set page number to last page
{
$pagenum = $last; //this will happen if user clicked the next page link when current page is the last page
}
//($pagenum - 1) * $page_rows calculates where to start the lmit
$query.= ' limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;//limit result
echo $query;
$filter_Result = mysqli_query($con, $query);//execute query with limits
//pagination links
echo 'First Page';
echo 'Previous Page';
echo 'Next Page';
echo 'Last Page';

Try this in a simple way.
<?php
$link = mysqli_connect("localhost","roo","","dbname");
if(!$link):
echo "something wrong with the database connection";
endif;
//check to see if the page (value) is available
if(isset($_GET['pageNo']):
$page = $_GET['pageNo'];
else:
$page = "";
endif;
if($page == "" || $page == 1):
$start_to_count_rowNo = 0;
else:
$start_to_count_rowNo = ($page * &item_displayed_per_page) - &item_displayed_per_page;
endif;
//here choose how many items do you want to display per page
&item_displayed_per_page = 10;
//Now select the data to display them
$query = "SELECT * FROM table_name LIMIT $start_to_count_rowNo, $item_displayed_per_page";
$readData = mysqli_query($link, $query);
//obtaining total number of data(rows) in a database
$sql = mysqli_query($link,"SELECT * FROM table_name");
$total_row = mysqli_num_rows($sql);
$pageNo = ceil($total_row / &item_displayed_per_page);
//using bootstrap add class pager in unordered list to style the list
?>
<ul class="pager">
<?php
//display out the page # like 1,2,3 ....
for($i = 0; $i <= $pageNo; $i++){
echo "</li><a href='pagename.php?pageNo={$i}'>{$i}</a></li>";
}
?>
</ul>

Related

Pagination does not display the last two data from the database

This is where I set the number of pages and starting point:
<?php
$connection = mysqli_connect("localhost", "root");
$db = mysqli_select_db($connection, 'db_hotelreservation');
if(isset($_GET['page'])){
$page = $_GET['page'];
}
else {
$page = 1;
}
$number_per_page = 02;
$start_from = ($page-1)*02;
echo "$start_from";
$query = "SELECT * FROM tbl_reservation WHERE room_status = 'Pending' OR room_status = 'Booked' LIMIT $start_from,$number_per_page";
$query_run = mysqli_query($connection, $query);
$resultCheck = mysqli_num_rows($query_run);
?>
This is where the looping and the buttons:
<?php
$query_result = "SELECT * FROM tbl_reservation WHERE room_status = 'Pending' OR room_status = 'Booked'";
$result_query = mysqli_query($connection,$query_result);
$total_records = mysqli_num_rows($result_query);
echo "Total Records: $total_records <br>";
$total_page = ceil($total_records/$number_per_page);
echo "Total Pages: $total_page <br>";
for($i=1;$i<$total_page;$i++){
echo "<a href='SuperAdminReserveManage.php?page=".$i."' class='btn btn-primary'>$i</a>";
}
?>
Total Records: 8
Total Pages: 4
But then it only prints 3 buttons, kinda confused where did I go wrong.
my guess is you're starting from 1 instead of 0
or use
for($i=1;$i<=$total_page;$i++){
....
instead

PHP dynamic previous/next links

I have a table called "product".
I'm displaying all the data from PHP product view page by using the id parameter.
With my code:
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
$query = "SELECT * FROM product WHERE id = $id ";
$select_product = $db->query($query);
while($row = $db->fetch_object($select_product)) {
$status = $row->status;
if($status == 'published') {
$title = $row->title;
echo $title;
}
}
I can pull all the data I need. In this example I can echo the title.
But how do I display a dynamic next page link? That goes same for previous link.
When I try with this code:
$query = "SELECT id FROM product";
$select_ids = $db->query($query);
while($row = $db->fetch_object($select_ids)) {
$ids = $row->id;
echo $ids;
}
I can see all the pages from that table. In my case they are 20,21,22...28
Next, I've tried like this:
$query = "SELECT id from product";
$select_ids = $db->query($query);
if($select_ids->num_rows > 0) {
$next = $id + 1;
echo 'Next';
} else {
}
With this code, my "next" link successfully goes to the next page. But, when it finishes with the result, in this case when I'm on page 28, the next dynamic link goes to empty page (29). Also this is not a good approach, because if some page, let's say 25 is deleted, the next link won't skip that page.
How can I improve that dynamic "next" link?
So first of all, you need two queries one for getting the data to display and another for counting the number of rows, also we'll need some additional variables.
Here comes the code:
$page = 1;
if(isset($_GET['page'])) {
$page = $_GET['page'];
}
$numberOfResultsPerPage = 10;
$offset = $numberOfResultsPerPage * ($page - 1)
$count = $db->query("SELECT COUNT(id) as num FROM product");
while($row = $db->fetch_object($count)) {
$numberOfRows = $row->num;
}
$query = "SELECT id FROM product LIMIT ". $offset.", ".$numberOfResultsPerPage;
$select_ids = $db->query($query);
while($row = $db->fetch_object($select_ids)) {
$ids = $row->id;
echo $ids;
}
if($page > 1) {
echo 'Prev';
}
if($page < ceil($numberOfRows / $numberOfResultsPerPage)) {
echo 'Next';
}
UPDATE:
In case you need to just find the next and previous product of the product this is the solution. It is not good if you'll have lots of products but in case the number of products is under 1000 there should not be any problems:
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
$query = "SELECT id from product";
$select_ids = $db->query($query);
$ids = array();
$i = 0;
while($row = $db->fetch_object($select_ids)) {
$ids[$i] = $row->id;
if($row->id == $id) {
$index = $i;
}
$i++;
}
if(isset($ids[$index-1])) {
echo 'Prev';
}
if(isset($ids[$index+1])) {
echo 'Next';
}

Problems with php pagination function

I have two php files:
1. functions.php
2. index.php
The functions.php file has a series of functions that query MySQL database to produce different result sets. For example, i have two functions; one that returns all data whose year 2016, and the other that returns all the data whose year is 2015.
For both queries i desire to have php pagination for the result sets returned. An example of the function that returns results for all data whose years are 2015 and 2016 looks like this:
function get2015(){
$con = dbConnect();
$refs_per_page = 20;
$query = "select * from mytable where year = 2015";
$sql=$con->prepare($query);
$sql->execute();
$total = $sql->rowCount();
$pages = ceil($total/$refs_per_page);
echo "$total <br>";
if (isset($_GET['page']) && is_numeric($_GET["page"])){
$page = (int) $_GET['page'];
}//endif
if($page =="" || $page ==1){
$page=0;
}
else{
$page = ($page * $refs_per_page)-$refs_per_page;
}
//
$query = "select * from mytable where year = 2015 limit $page, $refs_per_page";
$sql=$con->prepare($query);
$sql->execute();
$sql->setFetchMode(PDO::FETCH_ASSOC);
while ($row=$sql->fetch()){
$title = $row['title'];
$authors = $row['authors'];
echo "<b>$title</b>" . "<br>" . $authors . "<p>";
}
//
for($x=1; $x<=$pages; $x++){
?> <?php echo $x;?> <?php
}
}
//function get records for 2016
function get2016(){
$con = dbConnect();
$refs_per_page = 20;
$query = "select * from mytable where year = 2016";
$sql=$con->prepare($query);
$sql->execute();
$total = $sql->rowCount();
$pages = ceil($total/$refs_per_page);
echo "$total <br>";
if (isset($_GET['page']) && is_numeric($_GET["page"])){
$page = (int) $_GET['page'];
}//endif
if($page =="" || $page ==1){
$page=0;
}
else{
$page = ($page * $refs_per_page)-$refs_per_page;
}
//
$query = "select * from mytable where year = 2016 limit $page, $refs_per_page";
$sql=$con->prepare($query);
$sql->execute();
$sql->setFetchMode(PDO::FETCH_ASSOC);
while ($row=$sql->fetch()){
$title = $row['title'];
$authors = $row['authors'];
echo "<b>$title</b>" . "<br>" . $authors . "<p>";
}
//
for($x=1; $x<=$pages; $x++){
?> <?php echo $x;?> <?php
}
}
The code in index.php code looks like this
<?php
include "functions.php";
$page = $_GET["page"];
if($page){
if($page=="get2015"){
get2015();
}
if($page=="get2016"){
get2016();
}
}
?>
<html>
Archive<br>
2015<br>
2016<br>
</html>
<?php ?>
The first page renders okay but when i click on the second page the page goes blank. #Syed below has suggested the use of an offset variable, which while useful does the same thing as the $page variable in the code above. How do i get pagination to work? I highly suspect that the problem is how i am calling the pages on index.php
Your sould make $offset variable and minus 1 from it and then multiply by $per_page
For example
User in index.php your offset variable calculate like that.
// offset should be equal to 0 and query should be
// SELECT * FROM your_table WHERE year='2015' LIMIT 0, 20
(page=1 - 1) = 0 * $per_page = 20
User in index.php?page=2 your offset variable calculate like that.
// offset should be equal to 20 and query should be
// SELECT * FROM your_table WHERE year='2015' LIMIT 20, 20
(page=2 - 1) = 1 * $per_page = 20
// offset should be equal to 40 and query should be
// SELECT * FROM your_table WHERE year='2015' LIMIT 40, 20
(page=3 - 1) = 2 * $per_page = 40
$sql = sprintf("SELECT COUNT(*) FROM your_table WHERE year='%s'", $_GET['year']);
// Query to database and store in pages variable
$total_record = $con->query($sql)->result();
$page = ( isset($_GET['page']) && is_numeric($_GET['page'])) ? $_GET['page'] : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;
$pages = ceil($total/$per_page);
$sql = sprintf("SELECT * FROM your_table WHERE year='%s' LIMIT %s, %s", $_GET['year'], $offset, $per_page);
// QUERY TO DATABASE
for($i=1; $i<=$pages; $i++){
if ($page == $i) {
echo '<span class="active">'. $i .'</span>';
}else{
echo '' .$i .'';
}
}

PHP Pagination not functioning correcetly, stops on 6th page

I've recently got back into doing some PHP coding but have got stuck on something with PHP Pagination, it would seem that anything I tried either results in it not counting the pages and displaying on one page of results, or just stops at Page 6 and goes no further, I know with the data that is stored in the MySQL database, it should be showing 52 pages of results at 12 per page.
So I'm in need of some help, I thought it was working until I hit the won't go further than Page 6 after putting in 100's of entires into the database.
The code is as follows
<?php
//
//How to print date
//
if($print_date == 1)
{
$print_date = '%d.%m.%Y';
}
elseif($print_date == 2)
{
$print_date = '%m.%d.%Y';
}
elseif($print_date == 3)
{
$print_date = '%W, %M %D %Y';
}
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
} // if
$get_matches = mysql_query("SELECT
O.OpponentName AS hometeam, OP.OpponentName AS awayteam,
LM.LeagueMatchHomeGoals AS goals_home,
LM.LeagueMatchAwayGoals AS goals_away,
LM.LeagueMatchID AS id,
DATE_FORMAT(LM.LeagueMatchDate, '$print_date') AS date
FROM tplls_leaguematches LM, tplls_opponents O, tplls_opponents OP
WHERE O.OpponentID = LM.LeagueMatchHomeID AND
OP.OpponentID = LM.LeagueMatchAwayID AND
LeagueMatchSeasonID LIKE '$defaultseasonid'
ORDER BY LM.LeagueMatchDate");
$get_matches = #mysql_query($SQL) or die("Error Processing Fixtures");
$query_data = mysql_fetch_row($get_matches);
$numrows = $query_data[0];
$rows_per_page = 12;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
} // if
if ($pageno < 1) {
$pageno = 1;
} // if
$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$get_matches2 = mysql_query("SELECT
O.OpponentName AS hometeam, OP.OpponentName AS awayteam,
LM.LeagueMatchHomeGoals AS goals_home,
LM.LeagueMatchAwayGoals AS goals_away,
LM.LeagueMatchID AS id,
DATE_FORMAT(LM.LeagueMatchDate, '$print_date') AS date
FROM tplls_leaguematches LM, tplls_opponents O, tplls_opponents OP
WHERE O.OpponentID = LM.LeagueMatchHomeID AND
OP.OpponentID = LM.LeagueMatchAwayID AND
LeagueMatchSeasonID LIKE '$defaultseasonid'
ORDER BY LM.LeagueMatchDate, hometeam $limit",$connection)
or die(mysql_error());
while($row = mysql_fetch_array($get_matches2))
{
?>
More to add, if I take out the first SELECT statement, I get the same result?
Try this out. It's just your code with some minor modifications.
<?php
//
//How to print date
//
switch ($print_date)
{
case 1:
$print_date = '%d.%m.%Y';
break;
case 2:
$print_date = '%m.%d.%Y';
break;
case 3:
$print_date = '%W, %M %D %Y';
}
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
} // if
$clause = "
FROM tplls_leaguematches LM, tplls_opponents O, tplls_opponents OP
WHERE O.OpponentID = LM.LeagueMatchHomeID AND
OP.OpponentID = LM.LeagueMatchAwayID AND
LeagueMatchSeasonID LIKE '$defaultseasonid'
ORDER BY LM.LeagueMatchDate";
$query = "SELECT COUNT(*) as num $clause";
$result = #mysql_query($query) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
$rows_per_page = 12;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
} // if
if ($pageno < 1) {
$pageno = 1;
} // if
$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$query = "SELECT
O.OpponentName AS hometeam, OP.OpponentName AS awayteam,
LM.LeagueMatchHomeGoals AS goals_home,
LM.LeagueMatchAwayGoals AS goals_away,
LM.LeagueMatchID AS id,
DATE_FORMAT(LM.LeagueMatchDate, '$print_date') AS date $clause $limit";
$get_matches = mysql_query($query, $connection)
or die(mysql_error());
while($row = mysql_fetch_array($get_matches))
{
?>
It's actually what #g.salakirov suggested but in the context of all the code you supplied. I haven't tested it, but it should work. (Famous last words. :D)
You need to use mysql_num_rows(resource $result) rather than mysql_fetch_row(resource $result) to get the number of rows in here: .
$get_matches = #mysql_query($SQL) or die("Error Processing Fixtures");
$query_data = mysql_fetch_row($get_matches);
$numrows = $query_data[0];
$rows_per_page = 12;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
Alternatively, you can use a "count(*)" query in the beginning to get the number of entries, which will be significantly faster.
For example:
$get_matches = mysql_query("SELECT
count(*) as resultCount
FROM tplls_leaguematches LM, tplls_opponents O, tplls_opponents OP
WHERE O.OpponentID = LM.LeagueMatchHomeID AND
OP.OpponentID = LM.LeagueMatchAwayID AND
LeagueMatchSeasonID LIKE '$defaultseasonid'
ORDER BY LM.LeagueMatchDate");

How to get query to transfer to subsquent pages when paginating results

I've been going through all the pagination questions and answers on the site, and among all the long-drawn out code and OO solutions, this code is among the shortest and simplest:
<?php
// insert your mysql connection code here
$perPage = 10;
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$startAt = $perPage * ($page - 1);
$query = "SELECT COUNT(*) as total FROM table";
$r = mysql_fetch_assoc(mysql_query($query));
$totalPages = ceil($r['total'] / $perPage);
$links = "";
for ($i = 1; $i <= $totalPages; $i++) { $links .= ($i != $page ) ? "<a href='index.php?page=$i'>Page $i</a> " : "$page "; }
$query = "SELECT * FROM table ORDER BY title LIMIT $startAt, $perPage";
$r = mysql_query($query);
// display results here the way you want
echo $links; // show links to other pages
But I still can't see how to regenerate the query with the updated LIMIT on the subsequent pages. None of the messages make this clear, and I continue to get blank second pages no matter which code I try. I'd really appreciate it if someone could explain how to get the query results to the next pages.
I think you have to use the OFFSET token in your query. Like so:
$query = "SELECT * FROM table ORDER BY title LIMIT $perPage OFFSET $perPage * $page";
I hope this helps.
Not sure why you need to do select count(*) every time. I would suggest doing it like this:
<?php
/* establish the connection */
$mysqli = new mysqli (
'localhost', // The host to connect to
'username', // The user to connect as
'password', // The password to use
'dbname'); // The default database to query
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s<br />\n", mysqli_connect_error());
exit();
}
$perPage = 10;
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$startAt = $perPage * ($page - 1);
/* Send a query to the server */
if ($result = $mysqli->query(
"SELECT * FROM table ORDER BY title limit $startAt, $perPage")) {
$rowCnt = $result->num_rows;
echo "<h3>Page: $page</h3>\n";
/* Fetch the results of the query and show results*/
while( $row = $result->fetch_assoc() ) {
printf("%s - %s<br/>\n", $row['orderDate'], $row['orderDescription']);
}
/* Show next page, previous page links dynamically */
echo "<p>\n";
// generate previous page link if current page no is after 1st page
if ($page > 1)
printf("<a href='%s?page=%d'>Previous Page</a> \n",
$_SERVER["SCRIPT_NAME"], ($page-1));
// generate next page link if we were able to fetch $perPage rows
if ($rowCnt == $perPage)
printf("<a href='%s?page=%d'>Next Page</a>\n",
$_SERVER["SCRIPT_NAME"], ($page+1));
echo "</p>\n";
/* Destroy the result set and free the memory used for it */
$result->close();
}
/* close the connection */
$mysqli->close();
?>
I am using new mysqli extension of php, here is the php mysqli reference documentation

Categories