Solved

PHP Pagination help

Posted on 2013-01-10
4
227 Views
Last Modified: 2013-01-13
I have a search form that returns a number of results, in which I have paginated.  The problem is when I go to the 'Next' page, the url is redirected to ?pagenum=2 but the search results are lost.

Is there a way that I can keep the search results on the page, and just move from page to page, without passing each individual value to re-run the query each time?

<?php

$programid = "2036";

require_once($_SERVER['DOCUMENT_ROOT']."/includes/verifyaccess.php");
require_once($_SERVER['DOCUMENT_ROOT']."/includes/mainfunctions.php");
require_once($_SERVER['DOCUMENT_ROOT']."/includes/expFunctions.php");
require_once($_SERVER['DOCUMENT_ROOT']."/includes/expHeader.php");

if(isset($_POST['submit'])) 
	{
	if (isset($_GET['pageno'])) 
		{
		$pageno = $_GET['pageno'];
		}
	
	else 
		{
		$pageno = 1;
		}

	// Running the first query to return the number of rows found in resultset.
	if($_POST['kstatus'] == '1' && (!empty($_POST['kstatus'])))
		{
		$_POST['kstatus'] = 'A';
		}
		
	if($_POST['kstatus'] == '2' && (!empty($_POST['kstatus'])))
		{
		$_POST['kstatus'] = 'D';
		}

	if($_POST['kstatus'] == '3' && (!empty($_POST['kstatus'])))
		{
		$_POST['kstatus'] = 'S';
		}
				
    //define the list of fields
    $fields = array('kdaccount', 'name', 'phone', 'town', 'state', 'sic', 'referral', 'kstatus', 'nlrep');
	
	//put conditionals in an array
    $conditions = array();
	
	foreach($fields as $field)
		{
        // if the field is set and not empty
        if(isset($_POST[$field]) && $_POST[$field] != '') 
			{
			// create a new condition while escaping the value inputed by the user (SQL Injection)
			$conditions[] = "`$field` LIKE '%" . mysql_real_escape_string($_POST[$field]) . "%'";
			}
		}

	// builds the query
	$query = "SELECT name, kdaccount, nlrep, add1, add2, town, postcode, state FROM dw_names ";
		
	// if there are conditions defined
	if(count($conditions) > 0) 
		{
		// append the conditions
		$query .= "WHERE " . implode (' AND ', $conditions);

		if($_POST['comptype'] == '1' && (!empty($_POST['comptype'])))
			{
			$query .= " AND kdaccount REGEXP '^[0-9]+$'";
			}
			
		if($_POST['comptype'] == '2' && (!empty($_POST['comptype'])))
			{
			$query .= " AND kdaccount NOT REGEXP '^[0-9]+$'";
			}
			
		//Make sure the kdaccount does not begin with "Z" to remove vendor accounts from search.
		
		$query .= " AND kdaccount NOT LIKE 'Z%'";
		}
		
	//If no conditions are selected then we still need to run through the conditions listed above.
	else
		{
		$query .= 'WHERE hidden = "0"';

		if($_POST['comptype'] == '1' && (!empty($_POST['comptype'])))
			{
			$query .= " AND kdaccount REGEXP '^[0-9]+$'";
			}
			
		if($_POST['comptype'] == '2' && (!empty($_POST['comptype'])))
			{
			$query .= " AND kdaccount NOT REGEXP '^[0-9]+$'";
			}
			
		//Make sure the kdaccount does not begin with "Z" to remove vendor accounts from search.
		$query .= " AND kdaccount NOT LIKE 'Z%'";
		}
	
	$result = mysql_query($query) or trigger_error("SQL", E_USER_ERROR);
	$numrows = mysql_num_rows($result);
	
	//Now re-run the query with the same parameters to actually return the results.
	
	if($_POST['kstatus'] == '1' && (!empty($_POST['kstatus'])))
		{
		$_POST['kstatus'] = 'A';
		}
		
	if($_POST['kstatus'] == '2' && (!empty($_POST['kstatus'])))
		{
		$_POST['kstatus'] = 'D';
		}

	if($_POST['kstatus'] == '3' && (!empty($_POST['kstatus'])))
		{
		$_POST['kstatus'] = 'S';
		}
				
    //define the list of fields
    $fields = array('kdaccount', 'name', 'phone', 'town', 'state', 'sic', 'referral', 'kstatus', 'nlrep');
	
	//put conditionals in an array
    $conditions = array();
	
	foreach($fields as $field)
		{
        // if the field is set and not empty
        if(isset($_POST[$field]) && $_POST[$field] != '') 
			{
			// create a new condition while escaping the value inputed by the user (SQL Injection)
			$conditions[] = "`$field` LIKE '%" . mysql_real_escape_string($_POST[$field]) . "%'";
			}
		}

	// builds the query
	$query2 = "SELECT name, kdaccount, nlrep, add1, add2, town, postcode, state FROM dw_names ";
		
	// if there are conditions defined
	if(count($conditions) > 0) 
		{
		// append the conditions
		$query2 .= "WHERE " . implode (' AND ', $conditions);

		if($_POST['comptype'] == '1' && (!empty($_POST['comptype'])))
			{
			$query2 .= " AND kdaccount REGEXP '^[0-9]+$'";
			}
			
		if($_POST['comptype'] == '2' && (!empty($_POST['comptype'])))
			{
			$query2 .= " AND kdaccount NOT REGEXP '^[0-9]+$'";
			}
			
		//Make sure the kdaccount does not begin with "Z" to remove vendor accounts from search.
		
		$query2 .= " AND kdaccount NOT LIKE 'Z%'";
		}
		
	//If no conditions are selected then we still need to run through the conditions listed above.
	else
		{
		$query2 .= 'WHERE hidden = "0"';

		if($_POST['comptype'] == '1' && (!empty($_POST['comptype'])))
			{
			$query2 .= " AND kdaccount REGEXP '^[0-9]+$'";
			}
			
		if($_POST['comptype'] == '2' && (!empty($_POST['comptype'])))
			{
			$query2 .= " AND kdaccount NOT REGEXP '^[0-9]+$'";
			}
			
		//Make sure the kdaccount does not begin with "Z" to remove vendor accounts from search.
		$query2 .= " AND kdaccount NOT LIKE 'Z%'";
		}
				
	$rows_per_page = 10;
	$lastpage      = ceil($numrows/$rows_per_page);

	$pageno = (int)$pageno;

	if ($pageno > $lastpage) 
		{
	   $pageno = $lastpage;
		} 
		
	if ($pageno < 1) 
		{
	   $pageno = 1;
		}
		
	$limit = ' LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
			
	$query2 .=  $limit;

	$result2 = mysql_query($query2) or trigger_error("SQL", E_USER_ERROR);

	echo '<br /><br />' . $query2 . '<br /><br />';	
?>
<span class="sectitle">Search Results</span><br /><br />
 <div class="contentpane">
<strong>Your search has retuned <?=number_format($numrows); ?> rows.  </strong>
<br /><br />
<?php

if ($pageno == 1) 
	{
   echo " First Prev ";
	} 

else 
	{
   echo  "<span class='boldgreenlinks'><a href='?pageno=1'>First</a></span> ";
   $prevpage = $pageno-1;
   echo "<span class='boldgreenlinks'><a href='?pageno=$prevpage'>Prev</a></span> ";
	}
	
	echo " (Page $pageno of $lastpage) ";
	
if ($pageno == $lastpage) 
	{
   echo " Next Last ";
	} 
	
else 
	{
   $nextpage = $pageno+1;
   echo "<span class='boldgreenlinks'> <a href='?pageno=$nextpage'>Next</a></span> ";
   echo "<span class='boldgreenlinks'> <a href='?pageno=$lastpage'>First</a></span> ";
	}

?>
	<table id="contactSrchRes" border="0" cellspacing="0" class="tablesorter">
		<thead>
			<tr>
			<th class="columnheader" width="5%">Acct #</th>
			<th class="columnheader" width="20%">Company Name</th>
			<th class="columnheader" width="7%">Sales Rep</th>
			<th class="columnheader" width="20%">Address</th>
			<th class="columnheader" width="7%">City</th>
			<th class="columnheader" width="4%">State</th>
			<th class="columnheader" width="4%">Zip</th>			
			<th class="columnheader" width="6%">Last Activity</th>
			<th class="columnheader" width="6%">Add Activity</th>
			</tr>
		</thead>
		<tbody>
			<?php
		
	$i = 0;
			
			while($resultData = mysql_fetch_array($result2))
				{
				$i++;
				
				echo '<tr>
						<td><span class="nonboldblacklinks">'. $resultData['kdaccount'].'</span></td>
						<td><span class="nonboldblacklinks">'. $resultData['name'].'</span></td>
						<td><span class="nonboldblacklinks">'. getSalesCkName($resultData['nlrep']).'</span></td>
						<td><span class="nonboldblacklinks">'. $resultData['add1'] . ' ' . $resultData['add2'] . '</span></td>
						<td><span class="nonboldblacklinks">'. $resultData['town'] . '</span></td>
						<td><span class="nonboldblacklinks">'. $resultData['state']. '</span></td>
						<td><span class="nonboldblacklinks">'. $resultData['postcode'] . '</span></td>
						<td><span class="nonboldblacklinks">'. $addactivitylink . '</span></td>
						<td><span class="nonboldblacklinks">'. $activityData['due_date'] . '</span></td>
					 </tr>';
				}
			?>
		</tbody>
	</table>
<script type="text/javascript">
$(document).ready(function() { 
	$.tablesorter.defaults.widgets = ['zebra','saveSort']; 
    $("#contactSrchRes").tablesorter( {
		widthFixed: true,
		headers: { 
			9: { sorter: false} 
		}
	}); 
	
	$(function(){
		$("#contactSrchRes tr:even").addClass("even");
		$("#contactSrchRes tr:odd").addClass("odd");
	});
}); 
</script>
<?php 

require_once($_SERVER['DOCUMENT_ROOT']."/includes/footer.php"); 
}
?>

Open in new window

0
Comment
Question by:t3chguy
  • 2
4 Comments
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 38765646
without passing each individual value to re-run the query each time?

No.  The results that you got from the database with PHP are gone by the time it shows in the browser.  Each PHP page is a standalone program.  When the script is done running, all of it that you have not saved in a database, a file, or in $_SESSION variables is Gone.  That memory released to be used by the next program that is requested.
0
 
LVL 1

Author Comment

by:t3chguy
ID: 38765686
Would there be a simple way to do this with Ajax?  I really like how I've gotten the fields through an array and kind of build my query on the fly, but I'm worried that an Ajax solution would force me to use post variables differently.
0
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 38765738
There would not be a simpler way to do it with AJAX.  It would require what you already have plus the overhead of AJAX.

In the code you have posted, the '!empty' parts are redundant.  If a variable is equal to something, it is by definition '!empty'.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 38769016
The technically competent design would re-run the query on every page load, because the contents of the data base may have changed and the latest information is the correct information to display.  If the query is slow, that is a separate issue that may be addressed by table index and query structure.

The canonical article on PHP pagination (even though it appears to be old) is here.  Instead of thinking of it as "old" think "stood the test of time."
http://www.sitepoint.com/perfect-php-pagination/
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
How to Insert a File Using Text Editor 9 55
windows 10 bash shell 4 37
Phone Dialer 5 38
two tables one button 11 20
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now