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.
Related
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.
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.
It's been a month and am really messed up trying to integrate a php pagination code to my search script. Referred to most of the tutorials Googling, but in vain. Any help would be much appreciated. Here I go...
<?php
ob_start();
session_start();
$_GET['term'] = trim($_GET['term']);
$output = preg_replace('!\s+!', ' ', $_GET['term']);
if(empty($_GET['term'])|| preg_match("/^[#!#\$\^%&*()+=\-\[\]\\\';,\.\/\{\}\|\":<>\?\ _ ]+$/i", $_GET['term']) || $output== ' ' || $_GET['term']== "%24_GET%5B%27term%27%5D")
{
echo "<BR>";
echo "<BR>";
echo("Please enter a Valid Search term");
}
else
{
mysql_connect("localhost", "root", "root");
mysql_select_db("search");
$_GET['term'] = explode(' ', $_GET['term']);
foreach($_GET['term'] AS $_GET['term'])
{
$_GET['term'] = trim($_GET['term']);
$sql = mysql_query("SELECT DISTINCT * FROM searchengine WHERE pagecontent LIKE '%" . str_replace(' ', "%' AND pagecontent LIKE '%", $_GET['term'])."%' LIMIT 0,10");
while($ser = mysql_fetch_array($sql)) {
echo "<BR>";
echo "<b><u><a href='$ser[pageurl]'>$ser[title]</a></u></b>";
echo "<BR>";
echo("<span class='style_block'>{$ser['pagecontent']}</span>");
echo "<BR>";
echo ("<a href='$ser[pageurl]'>$ser[pageurl]</a>");
echo "<BR>";
echo "<BR>";
}
}
$count=mysql_num_rows($sql);
if($count==0)
{
echo "<BR>";
echo "<BR>";
echo "Sorry, No News material was found... Please refine your search criteria and try again.";
}
}
?>
Apart from the problems Luc M has mentioned in his comment (which you should certainly resolve before moving forward), you are almost there.
You need to consider a couple of points, really: How many records to display per page, and what page you are on. These will dictate the records you need to retrieve and display. So, how do you go about this?
The first point is covered in your code already through use of the LIMIT clause in your SQL query. The second point is a tiny bit more complex to start with. You need a way of identifying the page you are on. This is probably easiest to identify through a GET variable, for example http://site.com/search.php?page=2. Now, for implementing this, you want something along these lines:
$recordsPerPage = 10; // although you may want to have this as a GET or POST variable as well, so the user can decide
if(isset($_GET['page']) // this ensures a default value
{
$currentPage = $_GET['page'];
}
else
{
$currentPage = 1;
}
Then, for your SQL query, you want to build something like this:
$query = "SELECT * FROM table_name LIMIT " . $recordsPerPage . " OFFSET " . ($currentPage - 1)*$recordsPerpage . ";";
The OFFSET clause of SQL along with LIMIT basically says "Select this many records, starting from result number x". You offset on $currentPage - 1 because the first page doesn't want an offset, and the second page only wants an offset of however many records were shown on the first page, so on and so forth.
To create navigation for the paginated data, you want to find out how many records are in your result set, which can be done through the count($array) function of PHP. Then, to find the number of pages, simply use something like:
$numPages = ceil(count($array)/$recordsPerPage);
Where $array is your dataset from the SQL query. The ceil() function rounds the result up to the next integer.
Once you have this result, you simply need to output links to each page, which can be done simply with a for loop:
for($i = 0; i < $numPages; i++)
{
echo '<a href="/search.php?page="' . $i+1 . '>' . $i+1 . '</a>';
}
To create first, previous, next and last page links, you need to do something like:
$firstPage = 1;
$previousPage = $currentPage - 1; // you may want to check here or elsewhere to make sure you have no page zero
$nextPage = $currentPage + 1; // may also want to make sure you don't go past the last page
$lastPage = $numPages;
These values can then be put into your generated links.
Again, I will refer you to Luc M's comment... These need to be fixed, take a look at mysqli functions instead of the now-deprecated mysql_*() functions you're currently using, make sure you clean any user-inputted data before using it, and consider looking at the MVC design pattern.
Hopefully, this will help you out.
I had search through many websites and tried the different ways provided online, but it cant seen to work. It does not load the information when I click next, last, first, previous. It only loads the first page's result. Please help! Thank you in advance.
function retrieveName($fieldName)
{
$i=1;
if(isset($_GET[$fieldName]))
{
mysql_connect("localhost", "root") or die(mysql_error());
mysql_select_db("intern") or die(mysql_error());
//This checks to see if there is a page number. If not, it will set it to page 1
if (!(isset($pagenum)))
{
$pagenum = 1;
}
//Here we count the number of results
$intern = $_GET[$fieldName];
$data = mysql_query("SELECT p.`internName`, p.`internNRIC`, c.`internSchName` FROM `personaldetails` p, `currentinstitution` c WHERE c.`internNRIC`= p.`internNRIC` AND p.`internName` like '%$intern%' || p.`internNRIC` like '%$intern%' || c.`internSchName` like '%$intern%' GROUP BY p.internNRIC") or die(mysql_error());
$rows = mysql_num_rows($data);
//This is the number of results displayed per page
$page_rows = 1;
//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;
PRODUCTION. //This is your query again, the same one... the only difference is we add $max into it
$data_p = mysql_query("SELECT p.`internName`, p.`internNRIC`, c.`internSchName` FROM `personaldetails` p, `currentinstitution` c WHERE c.`internNRIC`= p.`internNRIC` AND p.`internName` like '%$intern%' || p.`internNRIC` like '%$intern%' || c.`internSchName` like '%$intern%' GROUP BY p.internNRIC $max ") or die(mysql_error());
//This is where you display your query results
while($row = mysql_fetch_array( $data_p ))
{
echo $i. ".";
echo " NRIC : ".$row['internNRIC'] ."";
echo "</br><br/>";
echo " Name : ". $row['internName'] . " Name of School :" . $row['internSchName'];
echo "</br><br/>";
$i++;
}
echo "<p>";
// This shows the user what page they are on, and the total number of pages
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&searchIntern=$intern'> <<-First</a> ";
echo "---Interns Search---";
$previous = $pagenum-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous&searchIntern=$intern'> <-Previous</a> ";
}
//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&searchIntern=$intern'>Next -></a> ";
echo "---Interns Search---";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last&searchIntern=$intern'>Last ->></a> ";
}
}else echo "Please enter your search.";
}
Not 100% about this, but it looks like you're using a local variable for $pagenum when you want to use either a parameter (good idea) or a global variable such as $_GET['pagenum']. You're also leaving yourself open to SQL injection. Use mysql_real_escape_string on all variables which need to be used in queries (like $intern).
As #cwallenpoole says, it looks like $pagenum is scoped outside of the function, and I'm guessing the function is written assuming that register_globals is on, which is generally a very bad thing. I've seen this cause plenty of issues when moving an old (inherited) site to a new server.
To fix that specific problem, replace:
if (!(isset($pagenum)))
{
$pagenum = 1;
}
with this:
$pagenum = isset($_REQUEST['pagenum']) ?
(int)$_REQUEST['pagenum'] :
1;
This sets $pagenum to the request's pagenum value, and defaults to 1 if the page number isn't in the request. It also casts the value to an int which should at least stop one injection attack vector. The rest of the function is another matter...
I am having problem in restricting search result page number in php page.
I am using 3 fields to select user input and displaying search results at the bottom . Whenever I select all fields, the page number goes on increasing at the bottom which equals to total number of pages in DB and hence stretches the page wide and hence changes the page layout.
What if I only want like 10 or 15 pages to display and rest of them to be shown by next-> which i m currently using for changing from page 1 to page 2. Image below 34 result which are total number of entries and I want only 15.
I am using following code:
$Nav="";
If($page > 1) {
$Nav .= "<A HREF=\"search.php?page=".
($page-1)."&countryCode=".
urlencode($country)."&linkageType=".
urlencode($linkage)."&college=".
urlencode($college) . "\"><< Prev</A>";
}
For($i = 1 ; $i <= $NumberOfPages ; $i++) {
If($i == $page) {
$Nav .= " <B>$i</B>";
}Else{
$Nav .= " <A HREF=\"search.php?page=".
$i."&countryCode=" .urlencode($country).
"&linkageType=".urlencode($linkage).
"&college=".urlencode($college)."\">$i</A>";
}
}
If($page < $NumberOfPages) {
$Nav .= " <A HREF=\"search.php?page=".
($page+1)."&countryCode=".urlencode($country).
"&linkageType=".urlencode($linkage)."&college=".
urlencode($college) . "\"> Next>></A>";
}
Echo "<BR><BR>" . $Nav;
echo "</center>";
what I am looking for is just Search results restricting to 15 pages instead some extra pages followed by next button tab.
$maxPages=15; //set up our max value
for($x=1;$x<=$numOfPages;$x++){ //make a loop of all avail pages
if($x==$maxPages){
echo" Next "; //if we have reaced our max number, show a next link
$x=$numOfPages+1; // and increment our loop counter PAST our max loopable value
}else{
echo" $x ";
}
}
not pretty, and not very well designed, but does work, and is at a beginner level for understanding..