Search database/Page Results

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

sparky753
Forum Commoner
Posts: 51
Joined: Fri Nov 03, 2006 10:39 am

Search database/Page Results

Post by sparky753 »

Hi,

I have a form with a text field (LastName). When the form is submitted with a name entered in the text field, it queries the database and displays the results on the same page. I have set it up so that the results show 10 records per page.

Problem is, I run the query and display the results based on whether a user has submitted the form -
if (isset($_POST['submit']))

So what happens is, the if statement determines that the form has been submitted, the first page shows up correctly with 10 records, the number of pages and the links to those pages are also displayed but when i click on any other page, it loads the original form without any results... obviously because when clicking on any of the other pages, the form has not been submitted and so the if statement is not going to cause the query to be run or for the results to be displayed.

Is there any other way to perform this conditional operation without testing for form submission? Let me rephrase my question - when we do a search, what is the best way to page results?

Thanks,
Sean
choppsta
Forum Contributor
Posts: 114
Joined: Thu Jul 03, 2003 11:11 am

Post by choppsta »

I normally store the search criteria data as session data.

The alternative is to output all the search criteria in the links to pass it between pages.

Code: Select all

<a href="page.php?page=2&criteria1=x&criteria2=y">Page 2</a>
Which get's very tedious.
sparky753
Forum Commoner
Posts: 51
Joined: Fri Nov 03, 2006 10:39 am

Post by sparky753 »

What's interesting is, the paging works great if i remove the 'if' statement that checks for form submission and if i hard-code the LastName in the query. So i know the paging code works. The moment i put in the 'if' statement, it generates the results for page 1 but not the others.

The reason i have the 'if' statement is so that i can check for form submission and accordingly submit a value that is entered in the text field to the query.
sparky753
Forum Commoner
Posts: 51
Joined: Fri Nov 03, 2006 10:39 am

Post by sparky753 »

choppsta, how do you store the search criteria in session variables?
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Post some code. It is hard to diagnose a situation without seeing what the parser is seeing.
sparky753
Forum Commoner
Posts: 51
Joined: Fri Nov 03, 2006 10:39 am

Post by sparky753 »

Everah | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


The form on "search4.php" submits results to "search5.php". I decided to handle the results on another page.

search4.php code:
[syntax="html"]<form action="search5.php" method="post" >
       <p align="center">Search for User by Last Name</p>
       <p align="center">
         <input type="text" name="LastName"> 
		 <input type="hidden" name="test" value="test">
       </p>
       <p align="center">
         <input type="submit" name="submit" value="Search"> 
       </p>
      </form>

-----

search5.php code:

Code: Select all

<?
	  	  echo "<center><a href='logout.php'> Logout </a></center>";
		  $display = 10;
	  	  

$lname=$_POST['LastName'];	  

if (!isset($lname)) {   

    echo '<td class="tmpl_sidebackgroundl"  width="158" valign="top" >&nbsp; </td></tr></table>';
	} else {
	  
	  
	  $query = "SELECT * from users WHERE LastName='$lname' ";
	  $result = mysql_query ($query);
         $num_records = @mysql_num_rows ($result);
	
	 if (isset($_GET['np'])) { // Already been determined.
		$num_pages = $_GET['np'];
	   } else {

	        if ($num_records > $display) { // More than 1 page.
			    $num_pages = ceil ($num_records/$display);
		     } else {
			  $num_pages = 1;
		     } // if $num_records > $display
	  }// if isset get np
	  
	  // Determine where in the database to start returning results.
	if (isset($_GET['s'])) { // Already been determined.
		$start = $_GET['s'];
	} else {
		$start = 0;
	}
    
	$query2 = "SELECT * FROM users WHERE LastName='$lname' LIMIT $start,$display";
	$result2 = mysql_query ($query2);
	$num = @mysql_num_rows ($result2);
	
		
	 if ($num > 0) {
	 echo '<br>
  	   <table border="1" class="cell" width="623px" align="center">
       <tr>
        <td width="78px" align="center" id="head"><strong> Last Name</strong></td>
		<td width="89px" align="center" id="head"><strong> First Name</strong></td>
		<td width="172px" align="center" id="head"><strong> Street Address</strong></td>
		<td width="39px" align="center" id="head"><strong> State</strong></td>
		<td width="63px" align="center" id="head"><strong> Zip</strong></td>
		<td width="67px" align="center" id="head"><strong> Date of Birth</strong></td>
	</tr>';
	   
   
	   if ($num_pages > 1){
		echo '<p>';
			// Determine what page the script is on.	
			$current_page = ($start/$display) + 1;
			
			// If it's not the first page, make a Previous button.
			if ($current_page != 1) {
				echo '<a href="search5.php?s=' . ($start - $display) . '&np=' . $num_pages . '">Previous</a> ';
		     }//end if current_page
		  
		  // Make all the numbered pages.
			for ($i = 1; $i <= $num_pages; $i++) {
				if ($i != $current_page) {
					echo '<a href="search5.php?s=' . (($display * ($i - 1))) . '&np=' . $num_pages . '">' . $i . '</a> ';
				} else {
					echo $i . ' ';
				}
			}//end for
			
			// If it's not the last page, make a Next button.
			if ($current_page != $num_pages) {
				echo '<a href="search5.php?s=' . ($start + $display) . '&np=' . $num_pages . '">Next</a>';
			}//end if current_page !
			
			echo '</p><br />';
			
		   } // End of links section. end if num_pages
		

	else {
	echo "<p> <center> There is no user by that name. Please enter another User Last Name</center></p>"; 
	} //end else
// } //end while boolean	
 
 }//end else isset

Everah | Please use[/syntax]

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

You should only use a form submit check to build the array result criteria. When traversing pages, you are are either going to need to pass the search criteria along with the other query string vars or store it in a cookie/session var to use later.

What I would recommend is reading up on pagination. That is what you are after.
sparky753
Forum Commoner
Posts: 51
Joined: Fri Nov 03, 2006 10:39 am

Post by sparky753 »

Sorry about the code formatting. Thanks for taking care of that and for your reply. I guess i'm not sure how to assign the submitted text field value to a session variable...
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

$_SESSION['SomeName'] = $foo.
sparky753
Forum Commoner
Posts: 51
Joined: Fri Nov 03, 2006 10:39 am

Post by sparky753 »

Thanks. but do i define this on the search page or on the page that displays the results?
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Assign the value when the value is presented. Then use it wherever sessions are instantiated in your script.

Code: Select all

<?php
$text-field-value = apply_your_validation($_POST['text-field-value']);

$_SESSION['session-var-name'] = $text-field-value;
?>
sparky753
Forum Commoner
Posts: 51
Joined: Fri Nov 03, 2006 10:39 am

Post by sparky753 »

Thanks...but i'm still not able to get it to work. I'm probably not implementing it correctly. I apologize but i'm a newbie to PHP, particularly sessions.

On the main Search page, "search4.php", I put in these lines of code:

Code: Select all

<?
	 if (!isset($_POST['submit'])) {
		  //do nothing
	  }
	  else {
	  $_SESSION['lname'] = $_POST['LastName'];
		  }
 ?>
Then, on the page processing the search and running the query, "search5.php", I replaced the code at the top

Code: Select all

<?
	 $lname=$_POST['LastName'];        
         
         if (!isset($lname)) { 
 ?>
with this code:

Code: Select all

<?
	 if (!isset($_SESSION['lname'])) {
 ?>
Then in the queries, I typed the following:

Code: Select all

$query = "SELECT * from users WHERE LastName='{$_SESSION['lname']}' ";
          $result = mysql_query ($query);
         $num_records = @mysql_num_rows ($result); 
          .
          .
          .
         $query2 = "SELECT * FROM users WHERE LastName='{$_SESSION['lname']}' LIMIT $start,$display";
        $result2 = mysql_query ($query2);
        $num = @mysql_num_rows ($result2);
I now get 2 errors:

Code: Select all

Notice: Undefined variable: num_records in /var/www/html/search5.php on line 150

Notice: Undefined index: lname in /var/www/html/search5.php on line 164
Line 164 is the second query. If the variable has not been passed correctly from the 'search4.php' page, why is there no error for the first query? Also 'num_records' seems to be defined. Please help!!!
sparky753
Forum Commoner
Posts: 51
Joined: Fri Nov 03, 2006 10:39 am

Post by sparky753 »

Latest update:

on search5.php, I got rid of the if statement altogether

Code: Select all

<?
         if (!isset($_SESSION['lname'])) {
 ?>
Now i don't get the num_records error but both queries can't identify the variable 'lname'

Code: Select all

Notice: Undefined index: lname in /var/www/html/search5.php on line 142

Notice: Undefined index: lname in /var/www/html/search5.php on line 166
Is there something i'm supposed to do on 'search5.php' to use the session variable $_SESSION['lname']? On the main search page 'search4.php', i assigned it the value this way:

Code: Select all

$_SESSION['lname'] = $_POST['LastName'];
What am i doing wrong?
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Here's the logical flow (since this will affect a few of your pages to say the least)...

Check for a session var (say 'logged_in' for example) and if it is set, redirect to the page that a logged in user sees, otherwise show a form for logging in. If the user needs to log in, post their data from the login form, and if it validates, set session var(s) and redirect to the page that all logged in users see. On all subsequent pages, check for this logged_in session var, and only allow action on the page after this session var evaluates to true, else log them out and make them start over again.

Generic code flow...
index.php

Code: Select all

<?php
if (isset($_SESSION['logged_in'])) {
    header('Location: http://www.mysite.com/logged_in_page.php');
    exit;
} else {
    header('Location: http://www.mysite.com/log_in_form.php');
    exit;
}
?>
log_in_form.php

Code: Select all

<?php
if (isset($_SESSION['logged_in'])) {
    header('Location: http://www.mysite.com/logged_in_page.php');
    exit;
} else {
    // Show a form
}
?>
logged_in_page.php (and all other logged_in pages)

Code: Select all

<?php
if (!isset($_SESSION['logged_in'])) {
    header('Location: http://www.mysite.com/log_in_form.php');
    exit;
} else {
    // Allow them to do what they want
}
?>
sparky753
Forum Commoner
Posts: 51
Joined: Fri Nov 03, 2006 10:39 am

Post by sparky753 »

Funny thing is, i've actually got my session variables to work in terms of log in. I've set things up the way you mentioned - if the user's logged in, he/she's redirected to another page (a welcome page). I've also written code that would redirect the user to the login page if he/she tried to type the URL of the welcome page directly without logging in.

My biggest problem the last few days has been this Search. From the welcome page, the user can search for a list of users. I can pull up all the results on a page but this table has over 3 million records so i don't want all the results to appear on a single page. It's when i got into pagination that i ran into problems. I can't for the life of me perform a search for a last name and have the results show up in separate pages. This is where i'm trying to figure out the use of the session variable.

On logging in, i call this PHP file

Code: Select all

<?php
$session['id']=session_id();
$_SESSION['username']=$_POST['username'];
$_SESSION['first_name']=$rec['first_name']
?>
I use the first_name value to greet the user on entering the welcome page. And on subsequent pages, i begin my pages with

Code: Select all

session_start();
Where would i need to specify/register the session variable for the LastName text field posted when the search form is submitted?
Post Reply