I have a page with a drop down list and a button. When the button is clicked I run a query and return the results from my database 10 at a time with a page for each set of 10. When I click on the page 2 button it returns to the initial state of the SearchPage.
Initial State
Page Numbers
After page select
My Code
if(isset($_POST['submit'])
{
$varietal=$_POST['varietal'];
$results_per_page = 10;
$sql = "SELECT * FROM winery WHERE wine_primary = '" . $varietal . "' OR wine_secondary = '" . $varietal . "'";
$result = mysqli_query($conn,$sql);
$number_of_results = mysqli_num_rows($result);
$number_of_pages = ceil($number_of_results / $results_per_page);
if (!isset($_GET['page'])) {
$page = 1;
} else {
$page = $_GET['page'];
}
$this_page_first_result = ($page-1)*$results_per_page;
// Formatting and display code would be here (not shown)
// Here is the page change code
for($page=1;$page<=$number_of_pages;$page++)
{
echo '' . $page . '';
}
From what I see on this code, the $varietal value is recieved via a POST request, but the next page link is a GET request (hyperlinks cause GET HTTP Requests by default). When the link is clicked, $_POST['varietal'] doesn't exist, because $_POST only has values on POST requests. I suggest converting the link into a form with a submit button, and passing in the previously selected $varietal and next page number as hidden inputs.
Related
I've set up a search of my database with pages. There are two searches performed on this page, one for users and one for pets, but for now I am trying to get it to work with the pet search only. The search itself functions, and the results display properly for page 1 with the appropriate amount of linked pages after. My problem comes in when I try to go beyond the first page. I have checked the search itself and it brings up results in my database, but clicking the page link results in a 'No results' message. Here is my initial setup:
<?php
if (!isset ($_GET['page']) ) {
$page = 1;
} else {
$page = $_GET['page'];
}
$results_per_page = 10;
$page_first_result = ($page-1) * $results_per_page;
$num_results = 0;
include("includes/header.php"); // This is where the first search is performed to check for number of rows
if (!empty($pet_search_result)) {
$number_of_result = mysqli_num_rows($pet_search_result);
$num_results = mysqli_num_rows($pet_search_result);
}
else if (!empty($user_search_result)) {
$number_of_result = mysqli_num_rows($user_search_result);
}
else {
$number_of_result = 0;
}
$number_of_page = ceil ($num_results / $results_per_page);
?>
This is of course followed by the search where users enter parameters. This search works perfectly without pagination. After those have been entered, the code says this:
$queryConditions = $queryConditions . ' LIMIT ' . $results_per_page . ' OFFSET ' . $page_first_result;
$pet_search_result2 = mysqli_query($con, "SELECT * from pets WHERE $queryConditions");
Results are then displayed, and here is where the problem hits.
for($page = 1; $page<= $number_of_page; $page++) {
echo " <a style ='color: white;' href='?page=$page'> $page </a> | ";
}
Clicking the link to page 2 or any other page leaves the user on the search page with no results shown. I have checked and the proper page number is picked up on page 2, the offset is correct, and the search itself turns up the appropriate results when performed directly in the database.
I have tried using
htmlentities($_SERVER['PHP_SELF'])
and
$_SERVER['PHP_SELF']
so that it read:
echo " <a href='" . htmlentities($_SERVER['PHP_SELF']) . "?page=$page'> $page </a> | ";
or
echo " <a style ='color: white;' href='" . $_SERVER['PHP_SELF'] . "?page=$page'> $page </a> | ";
as the redirect url, and none of these worked. I was expecting clicking page 2 to show me the search page with the second set of 10 results. Instead it acts as if no search has been performed.
Okay so here my question i have a blog and i want to show user on first page only 5 posts so i execute this query
mysql_query("select * from posts LIMIT 5");
And then after showing 5 post i made a button named as: Show more posts
when user click on that button another PHP file(loadmoreposts.php) executed in which i execute this query
mysql_query("select * from posts LIMIT 5 OFFSET 5");
but i want to show user 5 post every time it clicks on that button so i make this loop in my PHP script loadmoreposts.php
include('dbConnectClass.php');
$connect = new doConnect();
$beforequery = mysql_query('select * from posts ORDER BY id DESC LIMIT 1;');
if (mysql_num_rows($beforequery) > 0) {
$max_public_id = mysql_fetch_row($beforequery);
$lastid = $max_public_id[0]; //Here it is
}else{
$lastid = "[0]";
}
echo "Last ID $lastid<br />";
$m=5;
for($n=5; $n<=15; $n++):
$afterQuery = mysql_query("select * from posts LIMIT $m OFFSET $m");
$m = $m+5;
$result = "";
while($row = mysql_fetch_assoc($afterQuery)){
$result .= "<div class='cd-timeline-block'>";
$result .="<div class='cd-timeline-img cd-warning'>";
$result .=" <i class='fa fa-pencil-square-o'></i>";
$result .="</div>";
$result .="<div class='cd-timeline-content'>";
$result .= "<h2>{$row['title']}</h2>
<p>{$row['content']}</p>
<img src='{$row['imagesrc']}' alt=''>
<br />
<span style='font-size:85%;'' class='label label-primary'>{$row['category']}</span>
</div>
</div>";
}
echo $result;
endfor;
Let me explain what i did in this script, first i connect to database by a class then i grab last id of my post(last updated post) by running $beforequery and then one more time i execute another query named as $afterquery and then i get my results
but i don't want to show all my posts only in one click i want to show them 5 at a time when user click on that button like first five are already showing but clicking on button will show 5 more then after clicking again it will show the next 5 posts.
this script is then grabbed by this AJAX script:
var loadmoreposts = function () {
$.post('assets/includes/fetchMoreRows.php').done(function( data ) {
$('#displaymoreposts').html(data);
});
}
This loadmoreposts(); fuction is running in onload="loadmoreposts();"body tag
Any Suggestions and help will be appreciated :)
============================
*EDITED**
===========================
I removed the loop and added this but not working
include('dbConnectClass.php');
$connect = new doConnect();
$m = $_POST['offset'];
$afterQuery = mysql_query("select * from posts LIMIT 5 OFFSET $m");
$result = "";
while($row = mysql_fetch_assoc($afterQuery)){
$result .= "<div class='cd-timeline-block'>";
$result .="<div class='cd-timeline-img cd-warning'>";
$result .=" <i class='fa fa-pencil-square-o'></i>";
$result .="</div>";
$result .="<div class='cd-timeline-content'>";
$result .= "<h2>{$row['title']}</h2>
<p>{$row['content']}</p>
<img src='{$row['imagesrc']}' alt=''>
<br />
<span style='font-size:85%;'' class='label label-primary'>{$row['category']}</span>
</div>
</div>" ;
// $result .= "<tr><td> {$row['name']}</td>"."<td> {$row['password']}</td></tr></p>";
}
echo $result;
and JS/AJAX script is now this
var offsetValue = 0;
var loadmoreposts = function () {
$.post( 'assets/includes/fetchMoreRows.php', { offset: offsetValue} ).done(function( data ) {
$('#displaymoreposts').html(data);
offsetValue += 5;
});
}
Your AJAX script needs to send the current value for OFFSET, starting with 0. Everytime you click on your Show more posts link, it increases the value by 5.
So you should change your AJAX script to:
var offsetValue = 0;
var loadmoreposts = function () {
$.post( 'assets/includes/fetchMoreRows.php', { offset: offsetValue} ).done(function( data ) {
$('#displaymoreposts').html(data);
offsetValue += 5;
});
}
In your PHP script, you can grab the offset value like that:
$m = $_POST['offset'];
Also don't increase LIMIT. Change your query to:
mysql_query("select * from posts LIMIT 5 OFFSET $m");
If you increase LIMIT, the script will return +5 more posts everytime.
Hope that helps.
You can simply send the offset in the AJAX request, and use that offset in your query, here are simple steps:
Load first 5 posts, make the value sent by AJAX "load more" button be 5
When "load more" button is clicked, take the value sent (in our case 5) and insert it in the query (hopefully using prepared statements for security) and retrieve next 5 posts and send back the 5 posts and the new value for "load more" button which is now 10 (can be calculated by adding 5 to the value you got from the AJAX request
repeat, by sending 10 when the "load more" button is clicked, retrieving next 5 posts starting at number/offset 10, returning the 5 posts and the new value for the "load more" button which is 15 (10 + 5)
and so on ...
Try this..
//variable to hold the offset
var offSet = 5; //initial value
//send this in your post request
$.post('url', {aOffset : offset }, function(returnedData) {
// do something here
//update the offset value
offset+=5; });
I am trying to make pagination from one post to the next post in a single blog post. The problem is that when I open an article with ID-1 and I click on the 'next' button I get a blank/empty page.
This is the post page, which gets the ID of the chosen post in blog.php. This is what I have so far. Any suggestions?
<?php
// include database connection
require_once 'database.inc.php';
$pdo = Database::connect();
if(isset($_GET['post_id']) && is_numeric($_GET['post_id'])){
$post_id = $_GET['post_id'];
// page is the current page, if there's nothing set, default is page 1
$page = isset($_GET['page']) ? $_GET['page'] : 1;
// set records or rows of data per page
$recordsPerPage = 1;
// calculate for the query LIMIT clause
$fromRecordNum = ($recordsPerPage * $page) - $recordsPerPage;
// select all data
$query = "SELECT * FROM posts WHERE post_id = $post_id LIMIT {$fromRecordNum}, {$recordsPerPage}";
$stmt = $pdo->prepare( $query );
$stmt->execute();
//this is how to get number of rows returned
$num = $stmt->rowCount();
//check if more than 0 record found
if($num>0){
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo '
// post body ';
}
}
// *************** <PAGING_SECTION> ***************
// ***** for 'first' and 'previous' pages
if($page>1){
// ********** show the previous page
$prev_page = $page - 1;
echo "
<a href='" . $_SERVER['PHP_SELF'] . "?page={$prev_page}'>
<div class='prev-btn control-nav text-left'>
<h5>Previous Post</h5>
</div>
</a>";
}
// find out total pages
$query = "SELECT COUNT(*) as total_rows FROM posts";
$stmt = $pdo->prepare( $query );
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$total_rows = $row['total_rows'];
$total_pages = ceil($total_rows / $recordsPerPage);
if($page<$total_pages){
// ********** show the next page
$next_page = $page + 1;
echo "<a href='" . $_SERVER['PHP_SELF'] . "?page={$next_page}'>
<div class='next-btn control-nav text-right'>
<h5>Next Post</h5>
</div>
</a>";
}
}
?>
It's not very clear from your question, but I think your problem is this, your code requires the post_id parameter to be set:
if(isset($_GET['post_id']) && is_numeric($_GET['post_id'])){
$post_id = $_GET['post_id'];
}
But in your next and prev page links, you're not setting a post_id parameter:
echo "<a href='" . $_SERVER['PHP_SELF'] . "?page={$next_page}'>
<div class='next-btn control-nav text-right'>
<h5>Next Post</h5>
</div>
</a>";
Your code is inherently relying on a single post being shown, as determined by the post_id. Here's what I suggest, change:
// select all data
$query = "SELECT * FROM posts WHERE post_id = $post_id LIMIT {$fromRecordNum}, {$recordsPerPage}";
to:
// select all data
$query = "SELECT * FROM posts LIMIT {$fromRecordNum}, {$recordsPerPage}";
of course, then, you won't be able to show a specific post, but then again it's hard to know what you're actually trying to achieve here.
Could you show it in a working website? It would be easier to tell what is wrong then, but from the code it looks like you are making the url wrong in your anchor href part.
$prev_page = $post_id - 1;
<a href='" . $_SERVER['PHP_SELF'] . "?post_id={$prev_page}'>
<div class='prev-btn control-nav text-left'>
<h5>Previous Post</h5>
</div>
</a>"
$next_page = $post_id + 1;
and the link is there made in same manner as previous one
as i am not sure what your server php self is returning and you shouldnt be adding the second ? symbol in it, if it already had it and u should use & i think for get parameters as ? is only used once after the script file name once. Or you are either missing the ID in your url.
Also blank/empty page might be crashing the script on that page and if u have errors turned off you wont see it in webpage and will have to go to your php errors log file to look for them
EDIT: as block quote wasnt showing correctly.
It is because first you get $post_id but then in the links you put $page which doesn't contain your ID. Try to change your nex&prev links like this:
<a href='" . $_SERVER['PHP_SELF'] . "?post_id=".$prev_page."'>
<a href='" . $_SERVER['PHP_SELF'] . "?post_id=".$next_page."'>
Also don't forget to change the line for $page here:
$page = isset($_GET['page']) ? $_GET['page'] : 1;
to this
$page = isset($_GET['post_id']) ? $_GET['post_id'] : 1;
This should do the trick.
what i have is a list of posts on a page then each post has an icon to add to favorites (also has a watch button but it works the exact same to this) when clicked it calls the page with the script to add this post to ur favorites list in the database. (before using ajax i used a php redirect which returned to the previous page) when the page gets refreshed the database gets checked for what posts you have on your favorites list and will show the appropriate image depending on if its on ur favorites list or not.
When i click the link it appears to do what it should (go to the page and runs the update query to the database) but rather than refresh the div it just clears it. when i press f5 to refresh the page the image now displays the ticked image as it should so the query to the database is made when i click and the div gets kind of refreshed but it requires a proper refresh for it to display.
echo '<div id = "favwatchbox'.$ID.'">';
if($_SESSION['Valid'] == "True" ){
$userid = $_SESSION['ID'];
$check= "SELECT * from UserFavoritePost WHERE UserID='$userid' AND PostID='$ID'";
$resultcheck = $db->query($check);
$num_resultcheck = $resultcheck->num_rows;
$checklater= "SELECT * from UserViewLaterPost WHERE UserID='$userid' AND PostID='$ID'";
$resultchecklater = $db->query($checklater);
$num_resultchecklater = $resultchecklater->num_rows;
$prelogin = $_SERVER["REQUEST_URI"];
if($num_resultcheck >= 1)
{
echo "<a id = 'favdel".$ID."' href='#'><img id='Fav' title='Favorited' src='images/site-design/Favoritecheck.png'></a>";
?>
<script>
$(function() {
$("#favdel<?echo$ID;?>").click(function(evt) {
$("#favwatchbox<?echo$ID;?>").load("sql-scripts/deletefavorite.php?post=<?echo $ID;?>&user=<?echo $userid;?>&pre=<?echo $prelogin;?>")
evt.preventDefault();
})
})
</script>
<?
}
else
{
echo "<a id = 'favadd".$ID."' href='#'><img id='Fav' title='Mark as Favorite' src='images/site-design/Favorite.png'></a>";
?>
<script>
$(function() {
$("#favadd<?echo$ID;?>").click(function(evt) {
$("#favwatchbox<?echo$ID;?>").load("phpincludes/markasfavorite.php?post=<?echo $ID;?>&user=<?echo $userid;?>&pre=<?echo $prelogin;?>")
evt.preventDefault();
})
})
</script>
<?
}
}
the page for deleting from favourites
<?php
include '../phpincludes/dbconnection.php';
$userid = $_GET['user'];
$postid = $_GET['post'];
$query = "DELETE FROM UserFavoritePost WHERE UserID='$userid' And PostId='$postid'";
$result = $db->query($query);
$presubmit = $_GET['pre'];
if($presubmit == "/myaccount.php")
{
header("location:".$presubmit."");
}
?>
i have included an img src in the delete from favorites php file and now when you click it does the update and updates the image but when i click the link again to re add to my favorites it just brings me to the top of the page. if i refresh and click it will then run the add script but it still isnt refreshing the div properly
i am trying to implement pagination. A set of 9 products are displayed at a time. then upon clicking on a "View More" button, the content of a div should refresh by AJAX and show the next set of 9 products..here's the php code
if(!isset($_SESSION['current'])){
$query = "SELECT MAX(addedon) AS addedon FROM tags";
$result = mysql_query($query);
report($result);
$dated = mysql_fetch_assoc($result);
$recent = $dated['addedon'];
$_SESSION['current'] = $recent;
}
$query = "SELECT id, addedon
FROM tags
WHERE addedon <= '{$_SESSION['current']}'
ORDER BY addedon DESC
LIMIT 9
";
$result = mysql_query($query);
report($result);
while($row = mysql_fetch_assoc($result)){
$_SESSION['current'] = $row['addedon'];
$id = $row['id'];
$query = "SELECT name, image, cost
FROM tags, stock
WHERE tags.id={$id} AND stock.tagid = tags.id
";
$result1 = mysql_query($query);
report($result1);
$prodInfo = mysql_fetch_assoc($result1);
$pname = $prodInfo['name'];
$pimg = $prodInfo['image']; //the path to the actual image
$pcost = $prodInfo['cost'];
echo "<div class=\"oneproduct\">";
echo "<h3>{$pname}</h3><br />";
echo "<img src=\"{$pimg}\" height=\"{$ht}\" width=\"85px\" alt=\"prodImg\" /><br />";
echo "<span>Rs. {$pcost}</span>";
echo "<input type=\"image\" src=\"images/addcart.png\" class=\"addBtn\" />";
echo "</div>";
}
after all the products would be fetched and displayed, the last product on the page is stored as 'current' variable of SESSION.
problem is: the ajax thing always returns the initial set of 9 products and as soon as i refresh the page, the next set of products are coming..how do i make my link change the content?
The ajax code:
$("#viewMore").bind('click', function(){
$.ajax({
url:'showNineProds.php',
type:'POST',
dataType:'html',
success:function(data){
$("div#nineproducts").html(data);
},
error:function(xhr, status){
alert("Problem");
},
complete:function(xhr, status){
}
});
});
showNineProds.php simply calls a function that has been written above..
The correct way to do this is for the client-side code to specify with parameters to the AJAX call which "page" of records to be fetched. By using a session variable like this, the server has no concept of which records to get at which time. It's always going to return the "next" result. So any time you load that web page, it's going to serve the "next" set of records. There's no way to page backward in the result set.
Basically, you would store in local JavaScript values (or hidden form elements on the page, however you feel comfortable storing a value on the page) the information of the current result set and your AJAX call would send the necessary information to the server to return the requested result set.
For example, you could have a local JavaScript value that says which start record you're seeing and your page size:
startRecord = 1;
pageSize = 10;
Then if you click your "next" button the AJAX call would supply parameters to the server telling it what to fetch:
startRecord + pageSize, pageSize
You'd want to add a little bit of logic to determine if you're on the first or last page to disable "prev" and "next" functionality, of course. And there's a lot more you can do (variable page sizes, filtering and searching, sorting, etc.) but this is the basic gist of it.
You don't seem to be sending back the info from the ajax call. basically yoi might be fetching the values on the DB but don't seem to be sending the data back to the call..
do you echo the result set in some format? I can't see that in the code. in any case you can't access the $session variables from the js... these are accessible server side in php.