Pagination not working in search

Hi everyone,

First of all I want to wish all a happy and prosperous new year. May 2012 bring you the best.

I have a page which reads from a mysql DB then displays the results. since there could be many results I have implemented pagination from an example I found online. Everything works fine, however, when I perform a search and use the pagination controls, it ignores the search.

I know why, but I don’t know how to fix it as I believe it needs a URL function of some sort. Basically my URL needs to be …/welcome.php?search=416&submit=Search&page=3 after performing the search, but I can’t get &page=3 after the search url only when displaying all records.

Wondering if any good souls out there can help me out with this? Much appreciated.

[php]

<?php include "include/session.php"; include "include/config.php"; ?> <? ////////////////////////////// BEGIN PAGINATION ////////////////////////// $tbl_name="myform"; //your table name // How many adjacent pages should be shown on each side? $adjacents = 3; /* First get total number of rows in data table. If you have a WHERE clause in your query, make sure you mirror it here. */ $query = "SELECT COUNT(id) as num FROM $tbl_name where active='True'"; $total_pages = mysql_fetch_array(mysql_query($query)); $total_pages = $total_pages[num]; /* Setup vars for query. */ $targetpage = "welcome.php"; //your file name (the name of this file) $limit = 5; //how many items to show per page $page = $_GET['page']; if($page) $start = ($page - 1) * $limit; //first item to display on this page else $start = 0; //if no page var is given, set start to 0 // First check if a form was submitted. // Since this is a search we will use $_GET if (isset($_GET['search'])) { $searchTerms = trim($_GET['search']); $searchTerms = strip_tags($searchTerms); // remove any html/javascript. if (strlen($searchTerms) < 1) { $error[] = "Search terms must be longer than 3 characters."; }else { $searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection. } // If there are no errors, lets get the search going. if (count($error) < 1) { $query = "SELECT * FROM $tbl_name WHERE "; // grab the search types. //$types = array(); //$types[] = isset($_GET['first_name'])?"first_name LIKE '%{$searchTermDB}%'":''; //$types[] = isset($_GET['last_name'])?"last_name LIKE '%{$searchTermDB}%'":''; //$types[] = isset($_GET['home_phone'])?"home_phone LIKE '%{$searchTermDB}%'":''; //$types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked) if (count($types) < 1) $types[] = "active='True' and first_name LIKE '%{$searchTermDB}%'"; // use the body as a default search if none are checked $types[] = "active='True' and last_name LIKE '%{$searchTermDB}%'"; $types[] = "active='True' and home_phone LIKE '%{$searchTermDB}%'"; $andOr = isset($_GET['matchall'])?'AND':'OR'; $query .= implode(" {$andOr} ", $types) . " order by id desc LIMIT $start, $limit"; // $result = mysql_query($searchSQL) or trigger_error("There was an error.
" . mysql_error() . "
SQL Was: {$searchSQL}"); if (mysql_num_rows($searchResult) < 1) { $error[] = "The search term provided {$searchTerms} yielded no results."; } } }else { $query=" SELECT * FROM $tbl_name where active='true' order by id desc LIMIT $start, $limit"; } $result = mysql_query($query); /* Setup page vars for display. */ if ($page == 0) $page = 1; //if no page var is given, default to 1. $prev = $page - 1; //previous page is page - 1 $next = $page + 1; //next page is page + 1 $lastpage = ceil($total_pages/$limit); //lastpage is = total pages / items per page, rounded up. $lpm1 = $lastpage - 1; //last page minus 1 /* Now we apply our rules and draw the pagination object. We're actually saving the code to a variable in case we want to draw it more than once. */ $pagination = ""; if($lastpage > 1) { $pagination .= "
"; //previous button if ($page > 1) $pagination.= "« previous"; else $pagination.= "« previous"; //pages if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "$counter"; else $pagination.= "$counter"; } } elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some { //close to beginning; only hide later pages if($page < 1 + ($adjacents * 2)) { for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) { if ($counter == $page) $pagination.= "$counter"; else $pagination.= "$counter"; } $pagination.= "..."; $pagination.= "$lpm1"; $pagination.= "$lastpage"; } //in middle; hide some front and some back elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) { $pagination.= "1"; $pagination.= "2"; $pagination.= "..."; for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) { if ($counter == $page) $pagination.= "$counter"; else $pagination.= "$counter"; } $pagination.= "..."; $pagination.= "$lpm1"; $pagination.= "$lastpage"; } //close to end; only hide early pages else { $pagination.= "1"; $pagination.= "2"; $pagination.= "..."; for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "$counter"; else $pagination.= "$counter"; } } } //next button if ($page < $counter - 1) $pagination.= "next »"; else $pagination.= "next »"; $pagination.= "
\n"; } ////////////////////////////////// END PAGINATION ///////////////////////// ////searchform variables //////// not sure if this is working // Set up our error check and result check array $error = array(); //$results = array(); ///////////search form //(count($error) > 0)?"The following had errors:
" . implode("
", $error) . "


":""; echo ""; echo ""; echo " "; echo ""; echo ""; echo "
Search For:
"; //(count($result) > 0)?"Your search term:" . implode("
", $searchTerms) . "

":""; echo "

 

 

"; /////////// Now let us print the table headers //////////////// $bgcolor="#f1f1f1"; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; //////////////// Now we will display the returned records in side the rows of the table///////// while($row = mysql_fetch_array($result)) { if($bgcolor=='#f1f1f1'){$bgcolor='#ffffff';} else{$bgcolor='#f1f1f1';} echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; } echo ""; echo "
 ID Entered [Y-M-D] First Name Last Name Age Home Phone Address City Postal Code
"; if($row[retrieved] == "") { echo ""; } else { echo " "; } echo " $row[id] $row[entered] $row[first_name] $row[last_name] $age $row[home_phone] $row[address] $row[address2] $row[city] $row[postal_code]
"; echo "

 

"; ////////////////////////////// End of displaying the table with records //////////////////////// ////////////////////////// BEGIN PAGINATION //////////////////////////// /****** build the pagination links ******/ ?> <?=$pagination?> <?php ////////////////////////// END PAGINATION //////////////////// echo ""; echo ""; echo ""; echo ""; echo "
"; ////////////////////////////////// end page content //////////////////////////////////////// [/php]

Replace:

[php]$targetpage = “welcome.php”;[/php]

with:

[php] $targetpage = “welcome.php?search=” . $_GET[‘search’] . “&submit=Search&”;[/php]

Then replace every instance of $targetpage? with {$targetpage}:

[php]$pagination.= “<a href=”{$targetpage}page=$prev">« previous";[/php]
[php] $pagination.= “<a href=”{$targetpage}page=$counter">$counter";[/php]
[php]$pagination.= “<a href=”{$targetpage}page=$counter">$counter";[/php]
[php] $pagination.= “<a href=”{$targetpage}page=$lpm1">$lpm1";
$pagination.= “<a href=”{$targetpage}page=$lastpage">$lastpage";[/php]
[php] $pagination.= “<a href=”{$targetpage}page=1">1";
$pagination.= “<a href=”{$targetpage}page=2">2";[/php]
[php]$pagination.= “<a href=”{$targetpage}page=$counter">$counter";[/php]
[php] $pagination.= “<a href={$targetpage}page=$lpm1”>$lpm1";
$pagination.= “<a href=”{$targetpage}page=$lastpage">$lastpage";[/php]
[php]$pagination.= “<a href=”{$targetpage}page=1">1";
$pagination.= “<a href=”{$targetpage}page=2">2";[/php]
[php] $pagination.= “<a href=”{$targetpage}page=$counter">$counter";[/php]
[php] $pagination.= “<a href=”{$targetpage}page=$next">next »";[/php]

Hi jSherz,

Thank you very much for the prompt response. I made the changes you recommended and they work for the search.

The problem I have now, is that when I read the database records (without a search) the pagination is trying to display search results which returns 0 records. Any ideas?

thanks again,
Ronaldo

After:

[php]////searchform variables //////// not sure if this is working
// Set up our error check and result check array
$error = array();
//$results = array();[/php]

You could add:

[php]if(mysql_num_rows($result) == 0) {
echo ‘No results found!’; // Some error message
exit;
}[/php]

Hey there again jSherz,

I appreciate the prompt response, but it’s still not working.

The issue is that when viewing all records the URL needs to be:

welcome.php?page=2

After doing a search the URL needs to be:

welcome.php?search=416&submit=Search&page=2

After implementing the first corrections you gave me the search worked, but without the search still doesn’t.

Any other suggestions?

Ahh I see what you mean now.

Try replacing:

[php]$targetpage = “welcome.php?search=” . $_GET[‘search’] . “&submit=Search&”;[/php]

With:

[php]if(isset($_POST[‘submit’])) {
$targetpage = “welcome.php?”;
} else {
$targetpage = “welcome.php?search=” . $_GET[‘search’] . “&submit=Search&”;
}[/php]

I must be doing something wrong, as it’s still not working. I pasted the entire code on here in case it helps. I am getting the same results as before.

any other ideas?

thanks again
[php]

<? ////// To update session status for plus_login table to get who is online //////// if(isset($_SESSION['id'])){ $tm=date("Y-m-d H:i:s"); $q=mysql_query("update plus_login set status='ON',tm='$tm' where id='$_SESSION[id]'"); //echo "

Welcome "; echo $_SESSION[userid]; echo "

"; /////////////////////////////// Begin page content ////////////////////////////////////// $current = 1; include_once ("include/menu.php"); echo "

 

"; ////////////////////////////// BEGIN PAGINATION ////////////////////////// $tbl_name="myform"; //your table name // How many adjacent pages should be shown on each side? $adjacents = 3; /* First get total number of rows in data table. If you have a WHERE clause in your query, make sure you mirror it here. */ $query = "SELECT COUNT(id) as num FROM $tbl_name where active='True'"; $total_pages = mysql_fetch_array(mysql_query($query)); $total_pages = $total_pages[num]; /* Setup vars for query. */ //$targetpage = "welcome.php?search=" . $_GET['search'] . "&submit=Search&"; if(isset($_POST['submit'])) { $targetpage = "welcome.php?"; } else { $targetpage = "welcome.php?search=" . $_GET['search'] . "&submit=Search&"; } $limit = 5; //how many items to show per page $page = $_GET['page']; if($page) $start = ($page - 1) * $limit; //first item to display on this page else $start = 0; //if no page var is given, set start to 0 ////// delete selected records $news_ids = $_POST['checkbox']; if (is_array($news_ids) && count($news_ids) > 0) { $q = "UPDATE $tbl_name set active = 'False' WHERE id IN(".implode(',', $news_ids).")"; mysql_query($q); } // First check if a form was submitted. // Since this is a search we will use $_GET if (isset($_GET['search'])) { $searchTerms = trim($_GET['search']); $searchTerms = strip_tags($searchTerms); // remove any html/javascript. if (strlen($searchTerms) < 1) { $error[] = "Search terms must be longer than 3 characters."; }else { $searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection. } // If there are no errors, lets get the search going. if (count($error) < 1) { $query = "SELECT * FROM $tbl_name WHERE "; // grab the search types. //$types = array(); //$types[] = isset($_GET['first_name'])?"first_name LIKE '%{$searchTermDB}%'":''; //$types[] = isset($_GET['last_name'])?"last_name LIKE '%{$searchTermDB}%'":''; //$types[] = isset($_GET['home_phone'])?"home_phone LIKE '%{$searchTermDB}%'":''; //$types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked) if (count($types) < 1) $types[] = "active='True' and first_name LIKE '%{$searchTermDB}%'"; // use the body as a default search if none are checked $types[] = "active='True' and last_name LIKE '%{$searchTermDB}%'"; $types[] = "active='True' and home_phone LIKE '%{$searchTermDB}%'"; $andOr = isset($_GET['matchall'])?'AND':'OR'; $query .= implode(" {$andOr} ", $types) . " order by id desc LIMIT $start, $limit"; // $result = mysql_query($searchSQL) or trigger_error("There was an error.
" . mysql_error() . "
SQL Was: {$searchSQL}"); if (mysql_num_rows($searchResult) < 1) { $error[] = "The search term provided {$searchTerms} yielded no results."; } } }else { $query=" SELECT * FROM $tbl_name where active='true' order by id desc LIMIT $start, $limit"; } $result = mysql_query($query); /* Setup page vars for display. */ if ($page == 0) $page = 1; //if no page var is given, default to 1. $prev = $page - 1; //previous page is page - 1 $next = $page + 1; //next page is page + 1 $lastpage = ceil($total_pages/$limit); //lastpage is = total pages / items per page, rounded up. $lpm1 = $lastpage - 1; //last page minus 1 /* Now we apply our rules and draw the pagination object. We're actually saving the code to a variable in case we want to draw it more than once. */ $pagination = ""; if($lastpage > 1) { $pagination .= "
"; //previous button if ($page > 1) $pagination.= "« previous"; else $pagination.= "« previous"; //pages if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "$counter"; else $pagination.= "$counter"; } } elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some { //close to beginning; only hide later pages if($page < 1 + ($adjacents * 2)) { for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) { if ($counter == $page) $pagination.= "$counter"; else $pagination.= "$counter"; } $pagination.= "..."; $pagination.= "$lpm1"; $pagination.= "$lastpage"; } //in middle; hide some front and some back elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) { $pagination.= "1"; $pagination.= "2"; $pagination.= "..."; for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) { if ($counter == $page) $pagination.= "$counter"; else $pagination.= "$counter"; } $pagination.= "..."; $pagination.= "$lpm1"; $pagination.= "$lastpage"; } //close to end; only hide early pages else { $pagination.= "1"; $pagination.= "2"; $pagination.= "..."; for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "$counter"; else $pagination.= "$counter"; } } } //next button if ($page < $counter - 1) $pagination.= "next »"; else $pagination.= "next »"; $pagination.= "
\n"; } ////////////////////////////////// END PAGINATION ///////////////////////// ////////// If no search results return this statement. ////////////// if(mysql_num_rows($result) == 0) { echo 'No results found!'; // Some error message exit; } ///////////search form //(count($error) > 0)?"The following had errors:
" . implode("
", $error) . "


":""; echo ""; echo ""; echo " "; echo ""; echo ""; echo "
Search For:
"; //(count($result) > 0)?"Your search term:" . implode("
", $searchTerms) . "

":""; echo "

 

 

"; /////////// Now let us print the table headers //////////////// $bgcolor="#f1f1f1"; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; //// query used to be here before pagination //////////////// Now we will display the returned records in side the rows of the table///////// while($row = mysql_fetch_array($result)) { ///// calcuate patient's age ///// $date_of_birth = $row[date_of_birth]; $age = floor((time() - strtotime($date_of_birth))/(60*60*24*365.2420)); //////////////////// if($bgcolor=='#f1f1f1'){$bgcolor='#ffffff';} else{$bgcolor='#f1f1f1';} echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; } echo ""; echo "
 ID Entered [Y-M-D] First Name Last Name Age Home Phone Address City Postal Code
"; if($row[retrieved] == "") { echo ""; } else { echo " "; } echo " $row[id] $row[entered] $row[first_name] $row[last_name] $age $row[home_phone] $row[address] $row[address2] $row[city] $row[postal_code]
"; echo "

 

"; ////////////////////////////// End of displaying the table with records //////////////////////// ////////////////////////// BEGIN PAGINATION //////////////////////////// /****** build the pagination links ******/ ?> <?=$pagination?> <?php [/php]

jSherz,

I think I got it working. I want to thank you for all your help. Here’s what I did.
[php]
if(isset($_GET[‘submit’])) {
$targetpage = “welcome.php?search=” . $_GET[‘search’] . “&submit=Search&”;
}else {
$targetpage = “welcome.php?”;
}
[/php]

Hope you have a great new year.

thanks,
Ronaldo

My mistake, I put a POST instead of a GET! Must be getting tired!!

[php]if(isset($_GET[‘submit’])) {
$targetpage = “welcome.php?”;
} else {
$targetpage = “welcome.php?search=” . $_GET[‘search’] . “&submit=Search&”;
}[/php]

thanks again for all your help!

Sponsor our Newsletter | Privacy Policy | Terms of Service