"Next" button doesn't refresh page with next 25 results - php

I have the code below and am trying to get the next 25 results from my sql table to appear on page. However, whenever I click the next button, no information is displayed. I have my offset = ($page - 1) * $items_per_page......I'm struggling to figure this out as it seems so simple compared the other code I've written, but is proving to be very elusive to me....any assistance would be greatly appreciated. My primary issue is that the next link does not provide the next 25 results and I'm unable to determine why and how to correct.
echo "<h3 style='text-align:center;'>Welcome to the Exchange Portal, " . $row['name'] . "! </h3>";
$items_per_page = 25;
$sql_count = "SELECT pin, title, title2, email, phone FROM crown_acura";
$result_cnt = mysqli_query($conn, $sql_count);
if(false === $result_cnt) {
throw new Exception('Query failed with: ' . mysqli_error());
} else {
$row_count = mysqli_num_rows($result_cnt);
// free the result set as you don't need it anymore
//mysqli_free_result($result_cnt);
}
echo $row_count;
echo " ";
if (!isset($_GET['Page'])) {
$Page = 1;
} else {
$Page = $_GET['Page'];
}
echo $page;
echo " ";
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
echo " ";
echo $page_count;
echo " ";
echo $items_per_page;
$offset = ($page-1)*$items_per_page;
//echo $paging_info;
//echo " ";
echo "<br />";
//Query for displaying results
$list_sql = "SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page";
$result_query = $conn->query($list_sql);
//Table for displaying query results
echo "<table class='verify'>";
echo "<tr >";
echo "<td><h3>Name</h3></td><td> </td><td><h3>E-mail</h3></td><td><h3>Phone</h3></td>";
echo "</tr>";
for($i = 1; $i<= $page_count; $i++) {
if ($result_query->num_rows > 0) {
// output data of each row
while($row3 = mysqli_fetch_array($result_query)) {
echo "<tr>";
echo "<td class='dltd2 dlcl'>" . $row3["title"] . "</td><td>" . $row3["title2"] . "</td><td><a href='mailto:" . $row3['email'] . "'>" . $row3["email"] . "</a> </td><td>" . $row3["phone"] . " </td>";
echo "</tr>";
}
} else {
echo "0 results";
}
}
echo "<tr></tr>";
$next_page = $page + 1;
$last_page = $page - 1;
if($paging_info['curr_page'] <= 1) {
echo "<tr>";
echo "<td></td><td colspan='2'><a class='loadlink' href='" . $_PHP_SELF . "'>Next 25</a></td><td></td>";
echo "</tr>";
} elseif ($paging_info['curr_page'] < $page_count) {
echo "<tr>";
echo "<td></td><td><a href='" . $_PHP_SELF . "?page=" . $last_page . "'>Prev 25</a></td><td><a href='" . $_PHP_SELF . "?page=" . $next_page . "'>Next 25</a></td><td></td>";
echo "</tr>";
} elseif ($paging_info['curr_page'] === $page_count) {
echo "<tr>";
echo "<td></td><td colspan='2'><a href='" . $_PHP_SELF . "?page=" . $last_page . "'>Prev 25</a></td><td></td>";
echo "</tr>";
}
echo "</table>";
}
}
}

Have you tried to run the rendered SQL.
Output to browser:
"SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page"

try this... and change $page for different values (2,3,...,etc)
<?php
$items_per_page = 25;
$sql_count = "SELECT pin, title, title2, email, phone FROM crown_acura";
$result_cnt = mysqli_query($conn, $sql_count);
if (false === $result_cnt) {
throw new Exception('Query failed with: ' . mysqli_error());
} else {
$row_count = mysqli_num_rows($result_cnt);
// free the result set as you don't need it anymore
//mysqli_free_result($result_cnt);
}
echo $row_count;
echo " ";
if (!isset($_GET['Page'])) {
$Page = 1;
} else {
$Page = $_GET['Page'];
}
echo $page;
echo " ";
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if ($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
echo " ";
echo $page_count;
echo " ";
echo $items_per_page;
$offset = ($page - 1) * $items_per_page;
//echo $paging_info;
//echo " ";
echo "<br />";
//Query for displaying results
$list_sql = "SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page";
$result_query = $conn->query($list_sql);
echo ("RESULTS: ".$result_query->num_rows());
?>

Related

PHP pagination isn't working and I'm not sure why

I feel like I ask a lot of questions.
Anyways, I'm writing pagination for some database entries, and it looks sound to me but it's only displaying the first 10 posts and nothing else when I click the links.
The whole shebang is right here:
<?php
$post_limit = 10;
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("failed to connect: " . $conn->connect_error);
}
$sql = "SELECT count(id) FROM $tablename";
$result = mysqli_query($conn, $sql);
if (!$result) {
echo "you fucked up";
} else {
echo $row["id"];
}
$row = mysqli_fetch_array($result, MYSQL_NUM);
$post_count = $row[0];
if(isset($_GET['page'])) {
$page = $_GET['page'] + 1;
$offset = $post_limit * $page;
} else {
$page = 0;
$offset = 0;
}
$post_left = $post_count - ($page * $post_limit);
$sql = "SELECT id, upvotes, downvotes, name, title, message, date, time FROM posts ORDER BY date DESC, time DESC LIMIT $offset, $post_limit";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<br><div id='messageBar'>";
echo " ❖ </b>";
echo "Posted by <b>";
echo htmlspecialchars($row["name"]);
echo "</b> on ";
echo $row["date"];
echo " at ";
echo $row["time"];
if (!empty($row['title'])) {
echo " - <b>";
echo htmlspecialchars($row["title"]);
echo "</b>";
}
echo "<span style='float: right'>#";
echo $row["id"];
echo "</span>";
echo "</div><div id='messageContent'>";
echo htmlspecialchars($row["message"]);
echo "<br><br><span id='commentLink'><a class='commentLink' href='thread.php?id=$row[id]'>view thread </a></span>";
echo "<br></div><br><hr>";
}
} else {
echo "<br>";
echo "<center><i>it's dusty in here</i></center>";
echo "<br>";
}
if ($page > 0) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a> | ";
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($page == 0) {
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($post_left < $post_limit) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a>";
}
$conn->close();
?>
The link for the next page appears at the bottom, but clicking it takes you to the page you're already on with the same 10 most recent posts.
I am trying to learn PHP as I go, so I appreciate any help. Thank you!
Instead of using $_GET please use $_SESSION to manage a counter.
Every time you go in this page you increment the counter.
So, you have to do this on the top of the page:
if(isset($_SESSION['counter'])) {
$page = $_SESSION['counter'] + 1;
$offset = $post_limit * $page;
} else {
$page = 0;
$offset = 0;
$_SESSION['counter']=0;
}
Try this.
By the way there is Datatables which do what you're looking for.
P.S. If you don't start sessions in some other points in your code, please put session_start(); in the first page (e.g., login.php) otherwise put on this page.
Fixed. Problem was here:
if ($page > 0) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a> | ";
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($page == 0) {
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($post_left < $post_limit) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a>";
}
The URL I was linking to wasn't supposed to have spaces around the = sign. It's still buggy, but it works.

pagination within if not working properly

I am building a search page where the user can search by a field and then the table is displayed.I am trying to implement pagination through php in it but the pagination is not working.Any guidelines to paginate will be helpful.I am presenting the code of one if where the user has entered 1st field and the other fields are left blank,there are other condition as well.
if($item!="" && $brand=="" && $model=="") {
$sql ="SELECT * FROM table WHERE Product LIKE '%".$item."%' ";
$result = mysql_query($sql);
//$result1 = mysql_query($sql1);
$r = mysql_fetch_array($result);
$p=$r['Product'];
$b=$r['Brand'];
$m=$r['Model'];
if ($item!=$p) {
echo "<font style=\"color:Red;\"><h3>No Item Found!!!</h3></font>";
} else {
echo "<table class='table table-striped table-bordered bootstrap-datatable datatable'>
<thead>
<tr>
<th>Item</th>
<th>Brand</th>
<th>Model</th>
<th>Dealer Price</th>
<th>Quantity</th>
<th>Description</th>
</tr>
</thead>";
if (!(isset($pagenum))) {
$pagenum = 1;
}
//Here we count the number of results
//Edit $data to be your query
$data = mysql_query("SELECT * FROM table WHERE Product='$item' ") or die(mysql_error());
$rows = mysql_num_rows($data);
//This is the number of results displayed per page
$page_rows = 10;
//This tells us the page number of our last page
$last = ceil($rows/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1) {
$pagenum = 1;
} elseif ($pagenum > $last) {
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$sqll ="SELECT * FROM table WHERE Product='$item' $max ";
$resultt = mysql_query($sqll);
echo "<tbody>";
while($row = mysql_fetch_array($resultt)) {
echo "<tr>";
echo "<td>" . $row['Product'] . "</td>";
echo "<td>" . $row['Brand'] . "</td>";
echo "<td>" . $row['Model'] . "</td>";
echo "<td>" . $row['Dprice'] . "</td>";
echo "<td>" . $row['Quantity'] . "</td>";
echo "<td>" . $row['Quality'] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
echo " --Page $pagenum of $last-- <p>";
// First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page.
if ($pagenum == 1) {
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> ";
echo " ";
$previous = $pagenum-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> ";
}
//just a spacer
echo " ---- ";
//This does the same as above, only checking if we are on the last page, and then generating the Next and Last links
if ($pagenum == $last) {
} else {
$next = $pagenum+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> ";
}
} elseif($item=="" && $brand!="" && $model=="") {
...so on
I have tried paginating the table,10 rows are visible in the first page,but on going to the next page no table is showing,although there are other data s in the table.
The error is that you must add at the top of first file
$pagenum = filter_input(INPUT_GET, 'pagenum', FILTER_SANITIZE_NUMBER_INT);
You can't access to $pagenum directly without assign it a value from $_GET param.
I hope this is useful!

PHP Pagination code not working

I am unable to do pagination. The code display all the data retrieve from the mysql. Please help me to get it right.....
function.php
function pagination($limit=5) //here limit is not taken by the code
{
//$limit=5; if I uncomment this line limit will work
global $admin;
$sql = "SELECT FOUND_ROWS();";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
$numrows = $row[0];
$pagelinks = "<div class=pagelinks>";
if ($numrows > $limit) {
if(isset($_GET['page'])){
$page = $_GET['page'];
} else {
$page = 1;
}
$currpage = $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'];
$currpage = str_replace("&page=".$page,"",$currpage);
if($page == 1){
$pagelinks .= "<span class='pageprevdead'>< PREV</span>";
}else{
$pageprev = $page - 1;
$pagelinks .= "<a class='pageprevlink' href='" . $currpage .
"&page=" . $pageprev . "'>< PREV</a>";
}
$numofpages = ceil($numrows / $limit);
$range = $admin['pageRange']['value'];
if ($range == "" or $range == 0) $range = 7;
$lrange = max(1,$page-(($range-1)/2));
$rrange = min($numofpages,$page+(($range-1)/2));
if (($rrange - $lrange) < ($range - 1)) {
if ($lrange == 1) {
$rrange = min($lrange + ($range-1), $numofpages);
} else {
$lrange = max($rrange - ($range-1), 0);
}
}
if ($lrange > 1) {
$pagelinks .= "..";
} else {
$pagelinks .= " ";
}
for($i = 1; $i <= $numofpages; $i++){
if($i == $page){
$pagelinks .= "<span class='pagenumdead'>$i</span>";
}else{
if ($lrange <= $i and $i <= $rrange) {
$pagelinks .= "<a class='pagenumlink' href='" . $currpage .
"&page=" . $i . "'>" . $i . "</a>";
}
}
}
if ($rrange < $numofpages) {
$pagelinks .= "..";
} else {
$pagelinks .= " ";
}
if(($numrows - ($limit * $page)) > 0){
$pagenext = $page + 1;
$pagelinks .= "<a class='pagenextlink' href='" . $currpage .
"&page=" . $pagenext . "'>NEXT ></a>";
} else {
$pagelinks .= "<span class='pagenextdead'>NEXT ></span>";
}
} else {
$pagelinks .= "<span class='pageprevdead'>
< PREV</span> ";
$pagelinks .= "<span class='pagenextdead'>
NEXT ></span> ";
}
$pagelinks .= "</div>";
return $pagelinks;
}'
index.php
$sql = "SELECT id FROM articles WHERE is_published=1 " .
"ORDER BY date_published DESC"; //this is the query to retrive data from mysql
$result = mysql_query($sql,$conn);
if (mysql_num_rows($result) == 0) {
echo " <br />\n";
echo " There are currently no articles to view.\n";
} else {
while ($row = mysql_fetch_array($result)) {
outputStory($row['article_id'],TRUE);
}
}
echo pagination($limit);`
This code is incomplete. However the first thing you need to do is add the $limit to the actual sql query:
$sql = "SELECT id FROM articles WHERE is_published=1 " .
"ORDER BY date_published DESC LIMIT {$limit}";
Try this.
Just create a mysql table called players with 3 fields:- id, firstname, lastname to check how the code is working.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
VIEW-PAGINATED.PHP
Displays all data from 'players' table
This is a modified version of view.php that includes pagination
*/
// connect to the database
include('dbconfig.php');
// number of results to show per page
$per_page = 2;
// figure out the total pages in the database
$result = mysql_query("SELECT * FROM players");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
echo "<p><a href='view.php'>View All</a> | <b>View Page:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='view-paginated.php?page=$i'>$i</a> ";
}
echo "</p>";
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th></th> <th></th></tr>";
// 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; }
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . mysql_result($result, $i, 'id') . '</td>';
echo '<td>' . mysql_result($result, $i, 'firstname') . '</td>';
echo '<td>' . mysql_result($result, $i, 'lastname') . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
// pagination
?>
<p>Add a new record</p>
</body>
</html>

Displaying data from database in table

I am trying to display data in table form with 3 columns. Each should have a main category with some drop down lists. I get all the information to display but all is in one column and the drop down information does not display with the correct heading.
echo "<table>";
while ($row = mysql_fetch_array($result)) {
$count = 1;
if ($count = 1) {
$sCatID = ($row['CatID']);
echo "<tr valign='top'><td><b><a href='#" . $sCatID . "'>" . $sCatID . "</a></b><br>";
// column 1 categories
$result2 = mysql_query("SELECT * FROM test_prefixSubCat WHERE CatID=$sCatID");
// sub-cats
while ($row2 = mysql_fetch_array($result2)) {
$sSub = ($row2['CatID']);
$sSubID = ($row2['SubID']);
echo "<dd><a href='#'>" . $sSub . "</a><br>";
echo "</td>";
}
$count = 2;
} elseif ($count = 2) {
$sCatID = ($row['CatID']);
echo "<td><b><a href='.$sCatID.'>" . $sCatID . "</a></b><br>";
// column 1 categories
$result2 = mysql_query("SELECT * FROM test_prefixSubCat WHERE CatID=$sCatID");
// sub-cats
while ($row2 = mysql_fetch_array($result2)) {
$sSub = ($row2['CatID']);
$sSubID = ($row2['SubID']);
echo "<dd><a href='#'>" . $row2['Sub'] . "</a><br>";
echo "</td>";
}
$count = 3;
} elseif ($count = 3) {
$sCatID = ($row['CatID']);
echo "<td><b><a href='.$sCatID.'>" . $sCatID . "</a></b><br>";
// column 1 categories
$result2 = mysql_query("SELECT * FROM test_prefixSubCat WHERE CatID=$sCatID");
// sub-cats
while ($row2 = mysql_fetch_array($result2)) {
$sSub = ($row2['CatID']);
$sSubID = ($row2['SubID']);
echo "<dd><a href='.$sSub.'>" . $sSub . "</a><br>";
echo "</td></tr>";
}
$count = 1;
}
}
if ($count = 2) {
echo "<td> </td><td> </td></tr>";
} elseif ($count = 3) {
echo "<td> </td></tr>";
}
echo "</table>";
It doesn't seem to close the rows and table correctly... And it is also putting some of the drop down items before it displays the first heading.
If i display it in only one column it is working fine.
You should use == instead of single = in your if statements. Else it would execute everytime as that condition is always true.

php search from mysql database showing only one page

The following script is showing only first page and link to next page is there but is not leading anywhere. Can someone help me?
$var = #$_GET['q'] ;
$trimmed = trim($var);
$limit = 10;
if ($trimmed == "")
{
echo "<p>What are you looking for?...</p>";
exit;
}
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
mysql_connect('xxx', 'yyy', 'zzz');
mysql_select_db('yyy') or die('Unable to select database');
$query = "select * from table where NAME like '%$trimmed%' order by NAME";
$numresults = mysql_query($query);
$numrows = mysql_num_rows($numresults);
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>";
echo "<p><a href=\"http://www.google.com/search?q="
. $trimmed . "\" target=\"_blank\" title=\"Look up
" . $trimmed . " on Google\">Click here</a> to try the search on google</p>";
}
if (empty($s))
{
$s = 0;
}
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
echo "<p>You searched for: "" . $var . ""</p>";
echo "Results";
$count = 1 + $s;
while ($row= mysql_fetch_array($result))
{
$title = $row["NAME"];
echo "$count.- $title" ;
$count++ ;
}
$currPage = (($s/$limit) + 1);
echo "<br />";
if ($s >= 1)
{
// bypass PREV link if s is 0
$prevs = ($s - $limit);
print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><<
Prev 10</a> ";
}
$pages = intval($numrows/$limit);
if ($numrows % $limit)
{
$pages++;
}
if (!((($s+$limit)/$limit) == $pages) && $pages != 1)
{
$news = $s + $limit;
print "Next 10 >>";
}
$a = $s + ($limit);
if ($a > $numrows)
{
$a = $numrows;
}
$b = $s + 1;
echo "<p>Showing results $b to $a of $numrows</p>";
In your code, $s gets reset every time the page is reloaded or the next page link is clicked. You should have $s = $_REQUEST['s'] at the beginning of your code.
PHP_SELF is a $_SERVER variable. Regardless, you should use $_SERVER['SCRIPT_NAME'] here.
echo "Next 10 >>";
Among a few notable improvements, you should really look into sanitizing the variables you put in the querystring with urlencode() as well.

Categories