Jump to content

Pagination From Search Results


Go to solution Solved by richard2510,

Recommended Posts

Hi,

I have cobbled together the code from two tutorials, both of which work superbly on their own, but I must have something wrong in the code because together they don't work.

I have a database of chillies which is searchable. I want to add pagination when the results returned exceed 10. The problem is the first page of results returns 10 as it should, and at the bottom of the page there is the option to go to page two or next, but when you do, page 2 has no results and when you return to page one there are no results either.

The code is as follows;

        <h1>Chilli Search Results</h1>	
	<?php
	// Initilise search output variable
	$search_output = "";
	// Process the search query
	if(isset($_POST['searchquery'])) {
	// Filter user input
	$searchquery = preg_replace('#[^a-z 0-9?]#i', '', $_POST['searchquery']);
	$heat = $_POST['heat'];
		// Select Database
		mysql_select_db("allotmen_content") or die (mysql_error());
		if($heat != 'any'){
		$sqlcommand = "SELECT id, image1, common_name, url, url_short FROM chillies WHERE common_name LIKE '%$searchquery%' AND heat = '$heat'";
		}else{
		$sqlcommand = "SELECT id, image1, common_name, url, url_short FROM chillies WHERE common_name LIKE '%$searchquery%'";
		}
	$query = mysql_query($sqlcommand) or die(mysql_error());	
	$count = mysql_num_rows($query);
	
	
	if(empty($_POST['searchquery'])) {
	// If search box is empty
		echo 'Search box can not be empty. Please go back and enter some text <a href="chillies-homepage.php">BACK</a> <br /><br />';
	// If count is greater than 0
	}else if($count > 0) {
		$search_output .= "<hr /> $count Results for <strong>$searchquery</strong><hr /><br /><br />";
		
		if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
    $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
    //$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
    $pn = 1;
} 
//This is where we set how many database items to show on each page 
$itemsPerPage = 10; 
// Get the value of the last page in the pagination result set
$lastPage = ceil($count / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
    $pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
    $pn = $lastPage; // force it to be $lastpage's value
} 
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
    $centerPages .= '  <span class="pagNumActive">' . $pn . '</span>  ';
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a>  ';
} else if ($pn == $lastPage) {
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a>  ';
    $centerPages .= '  <span class="pagNumActive">' . $pn . '</span>  ';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a>  ';
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a>  ';
    $centerPages .= '  <span class="pagNumActive">' . $pn . '</span>  ';
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a>  ';
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a>  ';
} else if ($pn > 1 && $pn < $lastPage) {
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a>  ';
    $centerPages .= '  <span class="pagNumActive">' . $pn . '</span>  ';
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a>  ';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage; 
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("$sqlcommand ORDER BY common_name ASC $limit"); 

$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
    // This shows the user what page they are on, and the total number of pages
    $paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. '        ';
    // If we are not on page 1 we can place the Back button
    if ($pn != 1) {
        $previous = $pn - 1;
        $paginationDisplay .=  '   <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
    } 
    // Lay in the clickable numbers display here between the Back and Next links
    $paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
    // If we are not on the very last page we can place the Next button
    if ($pn != $lastPage) {
        $nextPage = $pn + 1;
        $paginationDisplay .=  '   <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
    } 
}


		while($row = mysql_fetch_array($sql2)) {
			$id 			= $row["id"];
			$image			= $row["image1"];
			$title 			= $row["common_name"];
			$url			= $row["url"];
			$url_short		= $row["url_short"];
			$search_output .= "<a href=\"$url_short\"><img src=\"images/$image\" width=\"100px\" height=\"100px\"/></a> $title - $url <br /><br />";	
		} // Close while	
	// If no results are found
	} else {
		$search_output = "<hr /><br /> Sorry, there are no results for <strong>$searchquery</strong>. <br /><br />Try entering <strong>$searchquery</strong> again but this time select <strong>'ANY HEAT'</strong> as the Heat Level<br /><br /><hr />";
		
		}
	}
	?>	  

		<?php echo $search_output; ?>
		<br />
		<?php echo $paginationDisplay; ?>

I'm guessing I have have something not quite right, I just can't see it. The page itself can been seen here http://www.allotment-web.org/chillies-homepage.php Search just the letter 'a' to bring more than 10 results and you'll see the issue. There seems little point increasing the number of varieties until I fix this pagination.

Any help greatly appreciated.

Richard

Link to comment
https://forums.phpfreaks.com/topic/281305-pagination-from-search-results/
Share on other sites

you must pass the search term(s) between pages. the easiest way of doing that is to use mode='get' in your search form so that the search terms are in the url query string/$_GET variables.

 

then you need to include those search terms in the pagination links. the easiest way of doing that is to use http_build_query(). you can set your pagination pn=x attribute in to the existing $_GET variables (i.e. $_GET['pn'] = x; ), then build the url query string using all the existing $_GET variables (i.e. $qs = http_build_query($_GET, '', '&'); ), then just echo this $qs variable in the url's you are building.

the suggestion in the second paragraph would look like -

$_GET['pn'] = $nextPage; // set $_GET['pn'] to the value you want in the link
$qs = http_build_query($_GET, '', '&'); // produce the url query string with all existing $_GET variables
$paginationDisplay .=  "   <a href='?$qs'> Next</a> "; // build pagination link

note: $_SERVER['PHP_SELF'], in some versions of php included the url query string and allowed cross site scripting and should not be used. you can leave it out and all current browsers will correctly produce a url that submits to the current page.
 

Hi Mac_gyver,

 

the suggestion in the second paragraph would look like -

$_GET['pn'] = $nextPage; // set $_GET['pn'] to the value you want in the link
$qs = http_build_query($_GET, '', '&'); // produce the url query string with all existing $_GET variables
$paginationDisplay .=  "   <a href='?$qs'> Next</a> "; // build pagination link

note: $_SERVER['PHP_SELF'], in some versions of php included the url query string and allowed cross site scripting and should not be used. you can leave it out and all current browsers will correctly produce a url that submits to the current page.
 

 

This worked  treat, thank you. The 'Next' and 'Back' buttons work perfectly, but I can't adapt the script to work for the numbers. Any advice?

 

Really appreciate it

 

Richard

It's this section of code I'm trying to adapt i believe;

$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
    $centerPages .= '  <span class="pagNumActive">' . $pn . '</span>  ';
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a>  ';
} else if ($pn == $lastPage) {
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a>  ';
    $centerPages .= '  <span class="pagNumActive">' . $pn . '</span>  ';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a>  ';
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a>  ';
    $centerPages .= '  <span class="pagNumActive">' . $pn . '</span>  ';
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a>  ';
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a>  ';
} else if ($pn > 1 && $pn < $lastPage) {
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a>  ';
    $centerPages .= '  <span class="pagNumActive">' . $pn . '</span>  ';
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a>  ';
}

I think it's this code which sets the number links between the 'Back' and 'Next' links. I've tried removing the $_SERVER['PHP_SELF'] and replacing it with various permutations of the previous code you gave me, but nothing looks right .

 

Cheers

 

Richard

Mac_gyver, 

 

So far the following code is the closest I've got,

if ($pn == 1) {
	$_GET['searchquery'];
	$sq = http_build_query ($_GET, '', '&');
    $centerPages .= '  <span class="pagNumActive">' . $pn . '</span>  ';
    $centerPages .= '  <a href="?' . $sq . 'pn=' . $add1 . '">' . $add1 . '</a>  ';

It works, but the url is incorrect. It shows 

 

http://www.allotment-web.org/chillies-search-results.php?searchquery=a&heat=any&submit=Searchpn%3D2&pn=1pn=2

 

whereas it should be

 

http://www.allotment-web.org/chillies-search-results.php?searchquery=a&heat=any&submit=Searchpn%3D2&pn=2

 

pn1 (page 1) is added in the url although it links to page 2 as it should.

 

Any ideas?

 

Richard

Edited by richard2510

this -

if ($pn == 1) {
    $centerPages .= '  <span class="pagNumActive">' . $pn . '</span>  ';
    $centerPages .= '  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a>  ';

would become -

if ($pn == 1) {
    $centerPages .= '  <span class="pagNumActive">' . $pn . '</span>  ';
    $_GET['pn'] = $add1; // set $_GET['pn'] to the value you want in the link
    $qs = http_build_query($_GET, '', '&'); // produce the url query string with all existing $_GET variables
    $centerPages .= "  <a href='?$qs'>$add1</a>  "; // build pagination link
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.