Why my pagination is not working? - php

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)

Related

need to fix mysqli_result code

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

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

Mysql_result() error

I'm trying to get pagination to work on my page, but running into a error:
mysql_result() expects parameter 1 to be resource, object given in
I think I need to use a mysqli command but can't seem to figure it out. Here is my code
$connect = mysqli_connect('localhost', 'root', 'password', 'vdb');
$per_page = 6;
$pages_query = mysqli_query($connect, "SELECT COUNT(id) FROM customers");
$pages = ceil(mysql_result($pages_query, 0) / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$query = mysqli_query($connect, "SELECT cid, fname, lname,address, score FROM customers");
while ($query_row = mysqli_fetch_assoc($query)) {
$array[] = $query_row['fname'] . '<br />';
}
if($pages >= 1)
{
for($x=1; $x <= $pages; $x++)
{
echo '' .$x.'';
}
}
Thanks in Advance!
You are jumbling between mysql and mysqli
$pages_query = mysqli_query($connect, "SELECT COUNT(id) FROM customers"); // MySQLi
$pages = ceil(mysql_result($pages_query, 0) / $per_page); // MySQL
There should be mysqli_result instead of mysql_result. Never mix them up and use just mysqli_* functions.
// line 3 of code above
$pages = ceil(mysqli_result($pages_query, 0) / $per_page);
^^

How can I get the pagination to work here?

I'm fairly new to coding, so I'm open to critique as well as help. I'm trying to apply pagination to my search results. I have returned the results I need, applied the limit and managed to get the pagination controls to present properly. However, when I select "next" or "previous" the pages have no results on. I'm sure there is something fundamentally wrong, but I just can't spot it.
?php
include_once("db_connex.php");
if (isset ($_POST ['search'])) {
$searchq = $_POST ['search'];
$count_query = mysql_query("SELECT * FROM activejobs WHERE jobtitle LIKE '%$searchq%' OR region LIKE '%$searchq%' AND status= '1'");
$count = mysql_num_rows($count_query);
// pagination starts here
if (isset($_GET['page'])) {
$page = pre_replace("#[^0-9]#","",$_GET['page']);
}
else {
$page = 1;
}
$perPage = 3;
$lastPage = ceil($count / $perPage);
if ($page < 1) {
$page = 1;
}
else if ($page > $lastPage) {
$page = $lastPage;
}
$limit = "LIMIT " . ($page - 1) * $perPage. ", $perPage";
$query = mysql_query("SELECT * FROM activejobs WHERE jobtitle LIKE '%$searchq%' OR region LIKE '%$searchq%' AND status= '1' ORDER BY jobid DESC $limit");
}
if ($lastPage != 1) {
if ($page != $lastPage) {
$next = $page + 1;
$pagination .= 'Next';
}
if ($page != 1) {
$prev = $page - 1;
$pagination .= 'Previous';
}
}
while ($row = mysql_fetch_array($query)) {
$jobtitle = $row['jobtitle'];
$region = $row['region'];
$salary = $row['salary'];
$jobdescription = $row ['jobdescription'];
$joburl = $row ['joburl'];
$output .= '<div id= "searchresults"><div id= "applybutton">Details</div><font id= "resultstitle">'.$jobtitle.'&nbsp-&nbsp'.$region.'&nbsp-&nbsp'.$salary.'</font><br>'.$jobdescription.'</div>';
}
?>
This kinds of if-else hell:
// pagination starts here
if (isset($_GET['page'])) {
$page = pre_replace("#[^0-9]#","",$_GET['page']);
}
else {
$page = 1;
}
can be solved like this (default it at start):
// pagination starts here
$page = 1;
if (isset($_GET['page'])) {
$page = pre_replace("#[^0-9]#","",$_GET['page']);
}
or even this (if you feel adventurous):
$page = (isset($_GET['page']) ? pre_replace("#[^0-9]#","",$_GET['page']) : 1);
Making a lot of If-else is easy at start and hard later, so keep it simple by reducing when you have nothing to do. Making your code smaller in a step closer to any solution.
Also this is common:
...
while ($row = mysql_fetch_array($query)) {
$jobtitle = $row['jobtitle'];
$region = $row['region'];
...
Why assigning $jobtitle to $row['jobtitle']; ?
It doesnt make your code easier, it just adds more code and making you read harder.
Give $row['X'] directly.
Also, as #ojovirtual stated you need to pass "$search" parameter everytime, otherwise your entire code block will be ignored ("$search" is not set)
Finally, when working with MySQL you need to check the values you feed your queries with,
in this example the $searchq. A malicious coder could make the $searchq look like a part of the query.
There is a simple fix for that:
Instead of plain:
$count_query = mysql_query("SELECT * FROM activejobs WHERE jobtitle LIKE '%$searchq%' OR region LIKE '%$searchq%' AND status= '1'");
make it a habit doing this:
$searchq = mysql_real_escape_string($searchq);
$count_query = mysql_query("SELECT * FROM activejobs WHERE jobtitle LIKE '%$searchq%' OR region LIKE '%$searchq%' AND status= '1'");
Not a universal solution but a starter before dive into new technologies as a starter.
This is a must for fields like username, password etc.
Finally, change from:
if (isset ($_POST ['search'])) {
$searchq = $_POST ['search'];
to:
if (isset ($_GET['search'])) {
$searchq = $_GET['search'];
You need to pass search again in your next and previuos buttons. A quick fix would be:
Change $_POST to $_REQUEST:
if (isset ($_REQUEST ['search'])) ...
Add the search to your next and previousbuttons:
$pagination.= 'Next';
Same with the previous button.
As someone stated, you should do some input sanitation before any database query.

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