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 .'';
}
}
Related
I am new to php so please be gentle. I have lookup up solutions within this forum on the exact same problem but am a little confused. I can't seem to figure out why the error
Call to undefined function mysqli_result() in line 10
keeps occurring.
Can anyone help please
<?php
include 'connection.php';
$per_page = 10;
$pages_query = mysqli_query($con,"SELECT COUNT('uniqueID') FROM 'business'");
$pages = mysqli_result($pages_query, 0) / $per_page;
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$query = mysqli_query($con,"SELECT 'manu' FROM 'business' LIMIT $start $per_page");
while ($query_row = mysqli_fetch_assoc($query)) {
echo '<p>', $query_row['manu'] ,'</p>';
}
?>
Try like this
<?php
include 'connection.php';
$per_page = 10;
$pages_query = mysqli_query($con,"SELECT COUNT('uniqueID') FROM 'business'");
$result = mysqli_fetch_row($pages_query); // <----- added
$pages = $result[0] / $per_page; // <------- modified
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$query = mysqli_query($con,"SELECT 'manu' FROM 'business' LIMIT $start $per_page");
while ($query_row = mysqli_fetch_assoc($query)) {
echo '<p>', $query_row['manu'] ,'</p>';
}
?>
<?php
include 'connection.php';
$per_page = 10;
$pages_query = mysqli_query($con,"SELECT COUNT('uniqueID') FROM 'business'");
$result = mysqli_fetch_row($pages_query); // <----- added
$pages = $result[0] / $per_page; // <------- modified
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$query = mysqli_query($con,"SELECT 'manu' FROM 'business' LIMIT $start $per_page");
while ($query_row = mysqli_fetch_assoc($query)) {
echo '<p>'. $query_row['manu'] .'</p>';
}
?>
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>
This is mysql connection coding, it is working fine
the same code i wrote with pdo connection,it is not working i'm new to php please help me to get out of this problem.
thanks in advance
<?php
error_reporting(0);
ini_set('max_execution_time', 600);
require_once 'config.php';
if(isset($_GET["nm_mask"]))
$nm_mask = $_GET['nm_mask'];
else
$nm_mask = "";
if(isset($_GET["cd_mask"]))
$cd_mask = $_GET['cd_mask'];
else
$cd_mask = "";
if(isset($_GET["func"]))
$func = $_GET['func'];
else
$func = "";
$where = "WHERE 1=1";
if($nm_mask!='')
$where.= " AND Login LIKE '$nm_mask%'";
if($cd_mask!='')
$where.= " AND Manager_Login LIKE '$cd_mask%'";
if($func!='')
$where.= " AND Function LIKE '$func%'";
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
if(!$sidx) $sidx =1; // connect to the database
$result = mysqli_query("SELECT COUNT(*) AS count FROM EmpMasterTB ".$where);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = $row['count'];
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
if ($limit<0) $limit = 0;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL = "SELECT * from EmpMasterTB ". $where ." ORDER BY $sidx $sord LIMIT $start , $limit";
$result = mysqli_query( $SQL ) or die("Couldn?t execute query.".mysqli_error());
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$responce->rows[$i]['id']=$row[WeekNo].$row[Login];
$responce->rows[$i]['cell']=array($row['WeekNo'],$row['WeekBeginning'],$row['SITE'],$row['Name'],$row['WFH'],$row['Login'],$row['Manager_Login'],$row['Lead'],$row['Cost_center'],$row['Business_Title'],$row['Function'],$row['Workgroup'],$row['Login_time'],$row['ROLE'],$row['Secondary_Skill'],$row['Weekoff'],""); $i++;
}
echo json_encode($responce);
?>
PDO connection code
<?php
error_reporting(0);
ini_set('max_execution_time', 600);
require_once 'config.php';
if(isset($_GET["nm_mask"]))
$nm_mask = $_GET['nm_mask'];
else
$nm_mask = "";
if(isset($_GET["cd_mask"]))
$cd_mask = $_GET['cd_mask'];
else
$cd_mask = "";
if(isset($_GET["func"]))
$func = $_GET['func'];
else
$func = "";
$where = "WHERE 1=1";
if($nm_mask!='')
$where.= " AND Login LIKE '$nm_mask%'";
if($cd_mask!='')
$where.= " AND Manager_Login LIKE '$cd_mask%'";
if($func!='')
$where.= " AND Function LIKE '$func%'";
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
if(!$sidx) $sidx =1; // connect to the database
$count = $dbh->exec("SELECT COUNT(*) AS count FROM EmpMasterTB ".$where);
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
if ($limit<0) $limit = 0;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL = "SELECT * from EmpMasterTB ". $where ." ORDER BY $sidx $sord LIMIT $start , $limit"; /*** The SQL SELECT statement ***/
$stmt = $dbh->query($SQL); /*** fetch into an PDOStatement object ***/
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
/*** echo number of columns ***/
$obj = $stmt->fetch(PDO::FETCH_OBJ);
/*** loop over the object directly ***/
{
$responce->rows[$i]['id']=$obj->WeekNo.$obj->Login;
$responce->rows[$i]['cell']=array($obj->WeekNo ,$obj->WeekBeginning ,$obj->SITE ,$obj->Name ,$obj->WFH ,$obj->Login ,$obj->Manager_Login ,$obj->Lead ,$obj->Cost_center ,$obj->Business_Title ,$obj->Function ,$obj->Workgroup ,$obj->Login_time ,$obj->ROLE ,$obj->Secondary_Skill ,$obj->Weekoff ); $i++;
}
echo json_encode($ );
?>
You have missed for loop and you didn't pass response in json_encode().
Please check my below code:
/*** echo number of columns ***/
$objs = $stmt->fetch(PDO::FETCH_OBJ);
/*** loop over the object directly ***/
foreach($objs as $obj)
{
$responce->rows[$i]['id']=$obj->WeekNo.$obj->Login;
$responce->rows[$i]['cell']=array($obj->WeekNo ,$obj->WeekBeginning ,$obj->SITE ,$obj->Name ,$obj->WFH ,$obj->Login ,$obj->Manager_Login ,$obj->Lead ,$obj->Cost_center ,$obj->Business_Title ,$obj->Function ,$obj->Workgroup ,$obj->Login_time ,$obj->ROLE ,$obj->Secondary_Skill ,$obj->Weekoff ); $i++;
}
echo json_encode($responce );
So I was trying to do pagination with php, but I can't quite get it done, there is an error of undefined index page in it somewhere, I have no idea why...here is my code:
<?php
$perpage = 10;
if (empty($_GET['page'])) {
$page = 1;
}else{
$page = $_GET['page'];
}
$limitstart = $_GET['page'] - 1 * $perpage;
$query = "SELECT * FROM images ORDER BY id DESC LIMIT '".$limitstart."', '".$perpage."' ";
$result = mysqli_query($con,$query) or die(mysqli_error($con));
while($row=mysqli_fetch_array($result)) {
?>
I appreciate your help in any way, thank you.
$limitstart = $_GET['page'] - 1 * $perpage;
is the same as (remember your math class)
$limitstart = $_GET['page'] - (1 * $perpage);
You would like to use
$limitstart = ($page - 1) * $perpage;
(also note the usage of your $page-variable)
The following code is working fine for the first page. It is a query based on user input from a form. I have 2 issues. The first one is when i click next page i get undefined index and undefined variable error which means the variables are not passed. The second question is how can i make a query and paginate it based on the user filled/selected values in the form? Some users may not fill all the values.
Here is my code: NB: The form method is GET. I have tried REQUEST and POST too. All the same error. Thanks in advance guys.
<?php
if (isset($_POST['Submit']))
$name = mysql_real_escape_string($_GET['name']);
$email = mysql_real_escape_string($_GET['email']);
$age = mysql_real_escape_string($_GET['age']);
$height = mysql_real_escape_string($_GET['height']);
include_once "conn.php"; //connect to db and table
$rs = mysql_query("SELECT COUNT(*) FROM people WHERE name='$name' AND email='$email' AND age='$age' AND height='$height'");
$rw = mysql_fetch_array($rs);
$numrows = $rw[0];
if ($numrows== 0) die("No Results Found");
$rowsperpage = 7;
$totalpages = ceil($numrows / $rowsperpage);
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
} else {
$currentpage = 1;
}
if ($currentpage > $totalpages) {
$currentpage = $totalpages;
}
if ($currentpage < 1) {
$currentpage = 1;
}
$offset = ($currentpage - 1) * $rowsperpage;
$query = mysql_query("SELECT * FROM people WHERE name='$name' AND email='$email' AND age='$age' AND height='$height' ORDER BY time DESC LIMIT $offset, $rowsperpage");
//print my tables here
while($row = mysql_fetch_array($query))
{
$uniqueid = $row['age'];
//output stuff here
}
//close sql
$range = 3;
if ($currentpage > 1) {
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1&name=$name&email=$email&age=$age&height=$height'> Go To Page 1</a> ";
$prevpage = $currentpage - 1;
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage&name=$name&email=$email&age=$age&height=$height'> Previous Page</a>";
}
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
if (($x > 0) && ($x <= $totalpages)) {
if ($x == $currentpage) {
echo " <font size=4 color=red>[<b>$x</b>] </font>";
} else {
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$x&name=$name&email=$email&age=$age&height=$height'>$x</a>";
}
}
}
if ($currentpage != $totalpages) {
$nextpage = $currentpage + 1;
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage&name=$name&email=$email&age=$age&height=$height'>Next Page</font></a>";
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages&name=$name&email=$email&age=$age&height=$height'>Last Page</a> ";
}
?>
The form submits as GET. Because this one, the POST variable isn't set. And you're not defining the first variable (missing brackets?). Furthermore, Submit is the only submitted value with a capital. Is this intentional?
if (isset($_GET['Submit'])) {
$name = mysql_real_escape_string($_GET['name']);
$email = mysql_real_escape_string($_GET['email']);
$age = mysql_real_escape_string($_GET['age']);
$height = mysql_real_escape_string($_GET['height']);
}
More ideally, because you want to ommit values, you'll probably want to check each variable individually for existence. And if it's not set (or empty), don't add that field in your WHERE clause.
$name = isset($_GET['name']) ? mysql_real_escape_string($_GET['name']) : null;
// ... process the other fields in same way ...
or spanned over multiple lines: EDIT: just noticed I was missing a closing ) in the two blocks below.
$name = null;
if (isset($_GET['name'])) {
$name = mysql_real_escape_string($_GET['name']);
}
// ... process the other fields in same way ...
or even:
$name = null;
if (isset($_GET['name']))
$name = mysql_real_escape_string($_GET['name']);
// ... process the other fields in same way ...
Dynamic query
Then, make your query a bit more dynamic. Like, adding all your available WHERE parameters to an array. It makes things easier.
// Store conditions in array
$whereConditions = array();
if (!empty($name)) {
$whereConditions['name'] = $name;
}
if (!empty($email)) {
$whereConditions['email'] = $email;
}
if ($age && $age > 0) {
$whereConditions['age'] = $age;
}
if ($height && $height > 0) {
$whereConditions['height'] = $height;
}
// Start building your query dynamically
$query = 'SELECT * FROM people';
// Making things easier here. Just flatten your array down.
$conditions = array();
foreach ($whereConditions as $field => $value) {
$conditions[] = sprintf("%s = '%s'", $field, $value);
}
// Join all conditions with AND
$where = implode(' AND ', $conditions);
// Add where clause, if there are conditions
if (!empty($where)) {
$query .= ' WHERE ' . $where;
}
$query .= " ORDER BY time DESC LIMIT {$offset}, {$rowsperpage}";
Final notes
Keep in mind to use prepared queries if you're allowing user input. And the mysql_ extension is deprecated. Switch to mysqli_ or PDO.