Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

PHP Pagination help

Posted on 2013-01-10
4
Medium Priority
?
238 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 84

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 84

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 111

Accepted Solution

by:
Ray Paseur earned 2000 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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
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…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

916 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