Jump to content

What's The Best Way Searching...


torque

Recommended Posts

So, I need to have the search results return to the same page.The script that initially querys the db doesn't seem to get the selected search terms unless I point the form action to it directly. The search function works perfectly in that case.Is it best to use session variables or is there a way to use post or get?I am a newbie @ this and have been studying hard to solve it. I am not sure if the problem is my syntax or my logic, but whenever I add isset or session variables it errors out my search script.Here is what I have now for the search.php:

<?phpheader("Content-type: text/xml" ); $con = mysql_connect('1', 'w', 'p');if (!$con){die('Could not connect: ' . mysql_error());}mysql_select_db("w"); $sql="SELECT * FROM r WHERE st='A'AND ver='Y'"; $cid = $_POST['cat'];if($cid != '') {// Category is selected$sql .= "AND cat = '$cid'";}$result = mysql_query($sql);$xml_output = "<?xml version=\"1.0\"?>\n"; $xml_output .= "<w>\n"; for($x = 0 ; $x < mysql_num_rows($result) ; $x++){ $row = mysql_fetch_assoc($result); $xml_output .= "\t<r>\n";	// Escaping illegal characters 		$row['b'] = str_replace("&", "&", $row['b']); 		$row['b'] = str_replace("<", "<", $row['b']); 		$row['b'] = str_replace(">", ">", $row['b']); 		$row['b'] = str_replace("\"", """, $row['b']);		  	$xml_output .= "\t\t<b>" . $row['b'] . "</b>\n"; //		 // Escaping illegal characters         $row['c'] = str_replace("&", "&", $row['c']);         $row['c'] = str_replace("<", "<", $row['c']);         $row['c'] = str_replace(">", ">", $row['c']);         $row['c'] = str_replace("\"", """, $row['c']);			$xml_output .= "\t\t<c>" . $row['c'] . "</c>\n";		 // Escaping illegal characters         $row['cat'] = str_replace("&", "&", $row['cat']);         $row['cat'] = str_replace("<", "<", $row['cat']);         $row['cat'] = str_replace(">", ">", $row['cat']);         $row['cat'] = str_replace("\"", """, $row['cat']);			$xml_output .= "\t\t<cat>" . $row['cat'] . "</cat>\n"; $xml_output .= "\t</r>\n"; } $xml_output .= "</w>"; echo $xml_output;mysql_close($con);?>

The page with the form looks like this:

<html xmlns:spry="http://ns.adobe.com/spry"><script src="../../../SpryAssets/xpath.js" type="text/javascript"></script><script src="../../../SpryAssets/SpryData.js" type="text/javascript"></script><script type="text/javascript"><!--var ds1 = new Spry.Data.XMLDataSet("search.php", "w/r");//--></script><form class="form" action="<?=$_SERVER[php_SELF]?>" method="POST"><table width="450" border="0">  <tr>    <td>Category</td>    <td><select name="cat" id="cid">      <option value="">All</option>            <?php		   $con = mysql_connect('1', 'w', 'p');if (!$con){die('Could not connect: ' . mysql_error());}mysql_select_db("w");$cate = @mysql_query("Select distinct category FROM cats");if(!$cate) {exit('<p>Unable to get category list.</p>');}			while($cat= mysql_fetch_array($cate)) {			$cid= $cat['category'];			$cname =htmlspecialchars($cat['category']);			echo "<option value ='$cid'>$cname</option>\n";			}			?>    			    </select>    </td>  </tr>  <tr>    <td colspan="2"><input type="submit" name="button" id="button" value="Submit"></td>    </tr></table></form><div spry:region="ds1">  <table width="508">    <tr>      <th>B</th>      <th>C</th>      <th>Cat</th>    </tr>    <tr spry:repeat="ds1">      <td>{b}</td>      <td>{c}</td>      <td>{cat}</td>    </tr>  </table></div>I would sure appreciate some help here.How do I rewrite the search script so it checks for the search terms before running the query?It seems to me the key problem is passing along the variable selected.
Link to comment
Share on other sites

Since the name of the select list is "cat" and it's submitting via post, you can find the value in $_POST['cat'].
It finds the value ok when I set the form action to search.php, it doesn't find it at all when I use self.I don't think the data is being passed somehow.I was reading your post about headers... is this anything that would work here?
Link to comment
Share on other sites

It shouldn't matter which page it is, any page would get the same data. If you want to see everything in post you can use print_r:print_r($_POST);
This page contains the following errors:error on line 1 at column 1: Document is emptyBelow is a rendering of the page up to the first error.I added the print_r($_POST);
Link to comment
Share on other sites

This page contains the following errors:error on line 1 at column 1: Document is emptyBelow is a rendering of the page up to the first error.I added the print_r($_POST);
If I am not getting any data passed, I get an empty document. Makes sense. I am trying to add sessions but keep getting errors. Here is the code & error message:
<?PHP session_start(); // start session$_session['search']= $_POST['Submit'];<html xmlns:spry="http://ns.adobe.com/spry">

Error:Parse error: syntax error, unexpected '<' in /blah/blah/catonly.php on line 5I am quite confused here and really appreciate your help!!!

Link to comment
Share on other sites

You need to end the PHP section before writing HTML code, or have the PHP print the HTML code. Don't just write HTML code inside a PHP block though.
Beautiful!! That worked!Now maybe I can figure out how to pass the info with the session and 'fill' my document! You ROCK!!!
Link to comment
Share on other sites

The session is easy to use, just make sure you capitalize it:$_SESSION['search']After you set that, you'll be able to use session_start on any other page, and then access the value in $_SESSION['search'].

Link to comment
Share on other sites

The session is easy to use, just make sure you capitalize it:$_SESSION['search']After you set that, you'll be able to use session_start on any other page, and then access the value in $_SESSION['search'].
Ok thanks, I will have to capitalize it and try again...<?phpsession_start(); // start sessionif(isset($_POST($_SESSION['search'])));Parse error: syntax error, unexpected '(', expecting ',' or ')' in blah/blah/search.php on line 3does the session_start have to be capitalized too?
Link to comment
Share on other sites

If I am not getting any data passed, I get an empty document. Makes sense. I am trying to add sessions but keep getting errors. Here is the code & error message:
<?PHP session_start(); // start session$_session['search']= $_POST['Submit'];<html xmlns:spry="http://ns.adobe.com/spry">

Error:Parse error: syntax error, unexpected '<' in /blah/blah/catonly.php on line 5I am quite confused here and really appreciate your help!!!

You have to close the PHP block:
<?phpsession_start(); // start session$_session['search']= $_POST['Submit'];?><html xmlns:spry="http://ns.adobe.com/spry">
Link to comment
Share on other sites

You have to close the PHP block:
This is a complete php page... no html.So I close after a session_start() always?Thanks! I thought it was only on the html.
Link to comment
Share on other sites

Nope, that didn't fix it.I think it has to do with my if(isset($_POST($_SESSION['search'])));I changed it to:if(isset($_POST[$_SESSION['search']]));That worked but now I get the document empty error again.If no data is passed shouldn't it still complete the html?

Link to comment
Share on other sites

Nope, that didn't fix it.I think it has to do with my if(isset($_POST($_SESSION['search'])));I changed it to:if(isset($_POST[$_SESSION['search']]));That worked but now I get the document empty error again.If no data is passed shouldn't it still complete the html?
Ok, it was the print_r that was erroring me out. I now display the html and initial data. There do not seem to be any session variables being passed though.The drop down continues to revert to the default.I am uncertain about my $_SESSION = value.'search' maybe should be submit?
Link to comment
Share on other sites

I think you're confusing yourself a little. I don't know what you were doing with print_r, but use it to show yourself the post and session data:

<pre><?phpprint_r($_POST);print_r($_SESSION);?></pre>

When you do this:$_POST[$_SESSION['search']]You're looking for a variable in post with the name of the value in the session. If $_SESSION['search'] is "test", then $_POST[$_SESSION['search']] is looking for $_POST['test']. I don't think that's what you want to do, are you using dynamic names for your post variables?

'search' maybe should be submit?
I don't know, should it? Did you save a variable in the session called "submit"? Print the session and post data and see what it is.Remember that you need to use session_start on any page that you want to use the session on, not only the page where you first use the session.
Link to comment
Share on other sites

I think you're confusing yourself a little. I don't know what you were doing with print_r, but use it to show yourself the post and session data:
<td>Category</td>    <td><select name="cat" id="cid">      <option value="">All</option>            <?php		   $con = mysql_connect('1', 'w', 'p');if (!$con){die('Could not connect: ' . mysql_error());}mysql_select_db("w");$cate = @mysql_query("Select distinct category FROM cats");if(!$cate) {exit('<p>Unable to get category list.</p>');}			while($cat= mysql_fetch_array($cate)) {			$cid= $cat['category'];			$cname =htmlspecialchars($cat['category']);			echo "<option value ='$cid'>[b]$cname[/b]</option>\n";			}			?>    			    </select>    </td>

I set the session as 'search' just to name it. I am not sure if that was correct or not?I made it = $_SESSION['search']= '$cname';'submit' is the button value. I am going to have to figure out what variable goes where.The pre PHP thing for print_r has me a bit stumped I have never seen that before. I put that at the beginning of the page before the php bracket? It would really be helpful to be able to see what my code is outputting! ? Ya Think? *grin*So, the session manual @php.net talks about setting something for a sid and adding it before session start?I have been getting really mixed up trying to understand the manual. I thought session_start() automatically generated an id? Do I need to 'name it ' some other way also?BTW.. you have really been patient I appreciate it! I really am trying to understand what I am doing as I have much to do and comprehension is mandatory. I am still very new at this and trying to wrap my mind around the logic involved. I am sorry I am so slow at 'getting it'.

Link to comment
Share on other sites

I set the session as 'search' just to name it. I am not sure if that was correct or not?
You have to name it something, one thing is as good as another.
I made it = $_SESSION['search']= '$cname';
If you have the single quotes around $cname, it's going to save the string "$cname" into $_SESSION['search']. If you want to save the value of the $cname variable, remove the single quotes around it.
The pre PHP thing for print_r has me a bit stumped I have never seen that before.
Pre tags in HTML mean pre-formatted text, it will show the text in a monospace font with all whitespace included, it doesn't ignore whitespace like other HTML elements do. Print_r prints an indented array structure, so wrapping it in the pre tags means that you'll see the indenting when you view the page. If you remove the pre tags, the HTML page will not include the indenting, but if you view the HTML source you'll see the regular output there.
I thought session_start() automatically generated an id? Do I need to 'name it ' some other way also?
It does generate an ID, it names it PHPSESSID and generates a randomized ID to use. You can change the default PHPSESSID to something else if you want to, but you don't have to.
Link to comment
Share on other sites

You have to name it something, one thing is as good as another.If you have the single quotes around $cname, it's going to save the string "$cname" into $_SESSION['search']. If you want to save the value of the $cname variable, remove the single quotes around it.Pre tags in HTML mean pre-formatted text, it will show the text in a monospace font with all whitespace included, it doesn't ignore whitespace like other HTML elements do. Print_r prints an indented array structure, so wrapping it in the pre tags means that you'll see the indenting when you view the page. If you remove the pre tags, the HTML page will not include the indenting, but if you view the HTML source you'll see the regular output there.It does generate an ID, it names it PHPSESSID and generates a randomized ID to use. You can change the default PHPSESSID to something else if you want to, but you don't have to.
Do I need to remove the single quotes from 'search' where I named it also?I added the pre print code and now return no results at all. The drop down continues to default to All when I click the submit button.I think that means that I am not getting the info passed with the session for some reason.I have been reading and am up against a wall again.The single quote info was priceless, I really thought that would solve it, not sure where to go from here.Again any help would be appreciated!
Link to comment
Share on other sites

Do I need to remove the single quotes from 'search' where I named it also?
You need to quote any strings. You don't need to quote variable names. Check here for information about the various data types in PHP, in your case search is a string value.http://www.php.net/manual/en/language.types.php
I think that means that I am not getting the info passed with the session for some reason.
Use print_r to print the session, see what data is there.
Link to comment
Share on other sites

You need to quote any strings. You don't need to quote variable names. Check here for information about the various data types in PHP, in your case search is a string value.http://www.php.net/manual/en/language.types.phpUse print_r to print the session, see what data is there.
Yeah, both of the arrays are empty {} curlies.I was excited to get it to print.I am still confused about the post variables versus the sessions.The search worked fine if I had the output going to a different page.The problem must then be somewhere in my isset function because adding that code negates the entire search process.Maybe just posting is all I should need here. I still want to learn sessions but really need to solve the search problem.the actual pages are at www.weatherradar.us/c.phpand www.weatherradar.us/s.phpThe list that shows up on s.php SHOULD be showing up on c.php below the drop down.The drop down is dynamically generated from a different table in the same mysql db.I have been reading your tutorial & tip posts, I will check this one out too.
Link to comment
Share on other sites

Show the code you're working with now.
Here is the code for c.php
<?PHP session_start(); // start session$_SESSION['search']= $cname;?><html xmlns:spry="http://ns.adobe.com/spry"><script src="../../../SpryAssets/xpath.js" type="text/javascript"></script><script src="../../../SpryAssets/SpryData.js" type="text/javascript"></script><script type="text/javascript"><!--var ds1 = new Spry.Data.XMLDataSet("s.php", "w/r");//--></script><form class="form" action="<?=$_SERVER[php_SELF]?>" method="POST"><table width="450" border="0">  <tr>    <td>Category</td>    <td><select name="cat" id="cid">      <option value="">All</option>            <?php		   $con = mysql_connect('1', 'w', 'p');if (!$con){die('Could not connect: ' . mysql_error());}mysql_select_db("w");$cate = @mysql_query("Select distinct category FROM cats");if(!$cate) {exit('<p>Unable to get category list.</p>');}			while($cat= mysql_fetch_array($cate)) {			$cid= $cat['category'];			$cname =htmlspecialchars($cat['category']);			echo "<option value ='$cid'>$cname</option>\n";			}			?>    			    </select>    </td>  </tr>  <tr>    <td colspan="2"><input type="submit" name="button" id="button" value="Submit"></td>    </tr></table></form><div spry:region="ds1">  <table width="508">    <tr>      <th>Business</th>      <th>City</th>      <th>Category</th>    </tr>    <tr spry:repeat="ds1">      <td>{bus}</td>      <td>{city}</td>      <td>{cat}</td>    </tr>  </table></div>

Here is s.php

<?PHP session_start(); // start session?><pre><?phpprint_r($_POST);print_r($_SESSION);?></pre><?php$con = mysql_connect('1', 'w', 'p');if (!$con){die('Could not connect: ' . mysql_error());}mysql_select_db("w"); $sql="SELECT * FROM referrals WHERE st='AL'AND ver='Y'"; $cid = $_POST['cat'];if($cid != '') {// Category is selected$sql .= "AND cat = '$cid'";}$result = mysql_query($sql);$xml_output = "<?xml version=\"1.0\"?>\n"; $xml_output .= "<w>\n"; for($x = 0 ; $x < mysql_num_rows($result) ; $x++){ $row = mysql_fetch_assoc($result); $xml_output .= "\t<r>\n";	// Escaping illegal characters 		$row['bus'] = str_replace("&", "&", $row['bus']); 		$row['bus'] = str_replace("<", "<", $row['bus']); 		$row['bus'] = str_replace(">", ">", $row['bus']); 		$row['bus'] = str_replace("\"", """, $row['bus']);		  	$xml_output .= "\t\t<bus>" . $row['bus'] . "</bus>\n"; 		 // Escaping illegal characters         $row['city'] = str_replace("&", "&", $row['city']);         $row['city'] = str_replace("<", "<", $row['city']);         $row['city'] = str_replace(">", ">", $row['city']);         $row['city'] = str_replace("\"", """, $row['city']);			$xml_output .= "\t\t<city>" . $row['city'] . "</city>\n";		 // Escaping illegal characters         $row['cat'] = str_replace("&", "&", $row['cat']);         $row['cat'] = str_replace("<", "<", $row['cat']);         $row['cat'] = str_replace(">", ">", $row['cat']);         $row['cat'] = str_replace("\"", """, $row['cat']);			$xml_output .= "\t\t<cat>" . $row['cat'] . "</cat>\n"; 		$xml_output .= "\t</r>\n"; } $xml_output .= "</w>"; echo $xml_output;mysql_close($con);?>

This code shows the proper opening page but doesn't search:

<html xmlns:spry="http://ns.adobe.com/spry"><script src="../../../SpryAssets/xpath.js" type="text/javascript"></script><script src="../../../SpryAssets/SpryData.js" type="text/javascript"></script><script type="text/javascript"><!--var ds1 = new Spry.Data.XMLDataSet("s.php", "w/r");//--></script><form action="<?=$_SERVER[php_SELF]?>" method="POST" name="search" class="form" id="search"><table width="450" border="0">  <tr>    <td>Category</td>    <td><select name="cat" id="cid">      <option value="">All</option>            <?php		   $con = mysql_connect('1', 'w', 'p');if (!$con){die('Could not connect: ' . mysql_error());}mysql_select_db("w");$cate = @mysql_query("Select distinct category FROM cats");if(!$cate) {exit('<p>Unable to get category list.</p>');}			while($cat= mysql_fetch_array($cate)) {			$cid= $cat['category'];			$cname =htmlspecialchars($cat['category']);			echo "<option value ='$cid'>$cname</option>\n";			}			?>    			    </select>    </td>  </tr>  <tr>    <td colspan="2"><input type="submit" name="button" id="button" value="Submit"></td>    </tr></table></form><div spry:region="ds1">  <table width="508">    <tr>      <th>Business</th>      <th>City</th>      <th>Category</th>    </tr>    <tr spry:repeat="ds1">      <td>{bus}</td>      <td>{city}</td>      <td>{cat}</td>    </tr>  </table></div>

Link to comment
Share on other sites

You've got the form on c.php submitting to itself, but it doesn't do anything with the postdata. s.php isn't going to have access to postdata unless a form gets submitted to it. I'm not sure how spry works, but it looks like you're trying to load the data set from s.php, but s.php is using $_POST. It's not going to have anything in $_POST unless you submit a form to it. $_POST doesn't last across requests, it sounds like you might want to have c.php save the postdata into the session when the form gets submitted and then have s.php use the session instead of $_POST.

Link to comment
Share on other sites

You've got the form on c.php submitting to itself, but it doesn't do anything with the postdata. s.php isn't going to have access to postdata unless a form gets submitted to it. I'm not sure how spry works, but it looks like you're trying to load the data set from s.php, but s.php is using $_POST. It's not going to have anything in $_POST unless you submit a form to it. $_POST doesn't last across requests, it sounds like you might want to have c.php save the postdata into the session when the form gets submitted and then have s.php use the session instead of $_POST.
So if I save the postdata into the session in c.php then an isset session code will allow s.php to first check if it has been submitted and if so, it will use that to perform its query?That means my $_POST cid in s.php would be replaced with a $_POST session instead?Spry basically just uses xml data in a table, the generation of the xml seems to be the issue here.You are absolutely right about the description of what happens. The data isn't getting posted back to itself on a reload with the submit button.The session has to be loaded into each page first then correct?I sure appreciate your help, I will study this a bit and try some things. I think you solved it I just have to wrap my mind around it. I am not sure how to write the code to do this, I have more studying to do!Is there a particular function to save the post data to the session or do I just create one?*THANKS!!!!*
Link to comment
Share on other sites

That means my $_POST cid in s.php would be replaced with a $_POST session instead?
That means that inside c.php you would save $_POST['cat'] to $_SESSION['cat'], and then inside s.php you would read the value in $_SESSION['cat']. You don't need a function to do that, you just assign the value:$_SESSION['cat'] = $_POST['cat'];
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...