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.
Related
How can I add pagination to a search engine results page?
I have build a search engine but there are hundreds of thousands of results for every search so I want to add pages to it.
The results of the search engine are outputted in a table.
I have started to learn php and sql recently...
How can I add those pages?
I have tried this so far but with no success:
<?php
$con = mysqli_connect(xxxx);
mysqli_select_db($con, 'Data') or die("could not find the database!");
$output = '';
$results_per_page = 1000;
//positioning
if(isset($_GET['search']))
{
$starttime = microtime(true); //TIME
$searchkey = $_GET['search'];
$query = mysqli_query($con, "SELECT * FROM table1 WHERE email LIKE '%$searchkey%'") or die("Could not search") ;
$count = mysqli_num_rows($query);
// count number of pages for the search
$number_of_pages = ceil($count/$results_per_page);
// determine which page number visitor is currently on
if (!isset($_GET['page']))
{
$page = 1;
}
else
{
$page = $_GET['page'];
}
// LIMIT
$this_page_first_result = ($page-1)*$results_per_page;
if ($count == 0)
{
echo "</br>";
$output = 'There are no search results !' ;
}
else
{
echo '<table class="myTable">';
echo "<tr><th>aaa</th><th>bbb</th></tr>";
$query = mysqli_query($con, "SELECT * FROM table1 WHERE email LIKE '%$searchkey%' LIMIT " . $this_page_first_result . ',' . $results_per_page" ") or die("Could not search") ;
while ($row = mysqli_fetch_array($query))
{
$email = preg_replace('/(' . $searchkey . ')/i', '<mark>\1</mark>', $row["aaa"]);
$password = $row['bbb'];
echo "<tr><td>";
echo $aaa;
echo "</td><td>";
echo $bbb;
echo "</td></tr>";
$output = '</table>';
}
//echo "</table>";
$endtime = microtime(true);
$duration = $endtime - $starttime;
echo "</br>";
if ($count == 1)
{
echo "<div class=resinfo>";
echo '<div>'."1 result was found for '$searchkey' in $duration seconds.".'</div>'.'</br>';
echo "</div>";
}
else
{
echo "<div class=resinfo>";
echo '<div>'."$count results were found for '$searchkey' in $duration seconds.".'</div>'.'</br>';
echo "</div>";
}
}
echo $output;
}
//LINKS to other pages
for ($page = 1; $page<=$number_of_pages;$page++){
echo '' . $page . '';
}
?>
What have I done wrong, what can I improve to make it work?
Thanks a lot for your help!
It is not a good idea to build a pagination from scratch, instead use a lib like this: https://github.com/KnpLabs/knp-components/blob/master/doc/pager/intro.md
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());
?>
I have been working at this all day and still at 8pm have had no luck. I was wondering if you guys can give me some advice on fixing it. I am building an Upload - gif sharing system for University.
Here is my code anyway -
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
mysql_connect("localhost","root","root") or die("Top Query");
mysql_select_db("UPLOAD") or die(mysql_error());
$count_query = mysql_query("SELECT NULL FROM details");
$count = mysql_num_rows($count_query);
//pagination
if(isset($_GET['page'])){
$page = preg_replace("#[^0-9]#","",$_GET['page']);
}else{
$page= 1;
}
$perPage = 5;
$lastPage = ceil($count / $perPage);
if($page < 1){
$page = 1;
}else if($page > $lastPage){
$page = $lastPage;
}
$limit = "LIMIT " .($page -1) * $perPage . ", $perPage";
//Query and gifs
$query = mysql_query("SELECT * FROM details ORDER BY date_added DESC") or die("2nd Query");
//Puts it into an array
$pagination="";
if($lastPage != 1){
if($page != $lastPage){
$next = $page + 1;
$pagination.='More';
}
if($page != 1){
$prev = $page - 1;
$pagination.='Back';
}
}
?>
And then the output in the html -
<?php
while($info = mysql_fetch_array($query)){
$shortlink = "".$info['photo']." " ;
//Outputs the image and other data
echo "<article class='upload-post'>" . "<div class='crop'>";
echo "<a href=uploads/".$info['photo'].">";
echo "<img class='scale-with-grid' src=uploads/".$info['photo'] .">"."</a>";
echo "</div>";
echo "".$info['name'] . "<br/>";
echo "Reaction ".$info['reaction'] ."<br/>";
echo "In " .$info['category'] ." <br/>";
echo "On " .$info['date_added'] ." <br/>";
echo "Link: $shortlink";
echo "</article>";
}
?>
<?php echo $pagination;?>
I can toggle between pages but its not limiting the number of posts displayed on the page. Id really appreciate the help as the deadline isn't too far away.
Thanks a bunch in advance!
You never append $limit to your query.
Try the follwing as a replacement...
...
//Query and gifs
$query = mysql_query("SELECT * FROM details ORDER BY date_added DESC ".$limit) or die("2nd Query");
//Puts it into an array
...
I have used this code before with no issues but... now I can't seem to load the page request when pressing Previous/Next Navigation if you can see where I went wrong be a help.
<?php
include 'config.php';
$db = mysql_connect($host, $username, $password);
mysql_select_db($db_name,$db);
$sql = "SELECT u_id FROM users";
$query = mysql_query($sql,$db);
$total_results = mysql_num_rows($query);
$limit = "5"; //limit of archived results per page.
$total_pages = ceil($total_results / $limit); //total number of pages
if (empty($page))
{
$page = "1"; //default page if none is selected
}
$offset = ($page - 1) * $limit; //starting number for displaying results out of DB
$query = "SELECT * FROM users ORDER BY u_id LIMIT $offset, $limit";
$result = mysql_query($query);
//This is the start of the normal results...
while ($row = mysql_fetch_array($result))
{
?>
<HR>
Username : <B><?echo $row['uname'] ?></B><BR>
user Message: <?echo $row['umess'] ?>
<BR>
<?
}
mysql_close();
// This is the Previous/Next Navigation stuff having issue with
echo "<font face=Verdana size=1>";
echo "Pages:($total_pages) "; // total pages
if ($page != 1)
{
echo "<a href=?&page=1><< First</a> "; // First Page Link
$prevpage = $page - 1;
echo " <a href=?page=$prevpage><<</a> "; // Previous Page Link
}
if ($page == $total_pages)
{
$to = $total_pages;
}
elseif ($page == $total_pages-1)
{
$to = $page+1;
}
elseif ($page == $total_pages-2)
{
$to = $page+2;
}
else
{
$to = $page+3;
}
if ($page == 1 || $page == 2 || $page == 3)
{
$from = 1;
}
else
{
$from = $page-3;
}
for ($i = $from; $i <= $to; $i++)
{
if ($i == $total_results) $to=$total_results;
if ($i != $page)
{
echo "<a href=?showold=yes&page=$i>$i</a>";
}
else
{
echo "<b><font face=Verdana size=2>[$i]</font></b>";
}
if ($i != $total_pages)
echo " ";
}
if ($page != $total_pages)
{
$nextpage = $page + 1;
echo " <a href=?page=$nextpage>>></a> "; // Next Page Link
echo " <a href=?page=$total_pages>Last >></a>"; // Last Page Link
}
echo "</font>";
?>
After a test run you can see 1st page request is fine untill you click next or a page number it keeps going back to 1st page.
Instead of
if (empty($page))
{
$page = "1"; //default page if none is selected
}
Try :
if (isset($_GET['page']))
{
$page = $_GET['page'];
}
else
{
$page = 1;
}
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.