How can I display tables fields based on a form input?

 
   $strName = isset($_REQUEST['frmSearch']['name'])?mysql_real_escape_string($_REQUEST['frmSearch']['name']):'';
    $strZipCode = isset($_REQUEST['frmSearch']['zipcode'])? mysql_real_escape_string($_REQUEST['frmSearch']['zipcode']):'';
    $strState = isset($_REQUEST['frmSearch']['zipcode'])?mysql_real_escape_string ($_REQUEST['frmSearch']['state']):'';/*)*/; 


 if(!empty($strZipCode)){
  $query4 = "SELECT state, zip, county
FROM stores
WHERE 
(zip= '$strZipCode'); 
$result = mysql_query($query4);
$arrstate = mysql_fetch_array($result);
echo '<div class="information"><label>County:</label>
        <div>'. $arrstate['county']. '</div>
	  <label>State:</label>
             <div>'. $arrstate['state']. '</div>
		   <label>Zip Code:</label>
             <div>'. $arrstate['zip']. '</div></div> <br><br>';
			 }

In the code above there is info $_RESQUESTed from a form coming from page1.php then it is use to display the fields County,State and zip from the table stores. as it is set up this fileds will display only WHERE (zip= ‘$strZipCode’); now it means that if a user select information from another fields and leave zipcode input fields empty the fields County,State and zip won’t display. Now how can I set the WHERE Clause to also display when users only input data in the state input field at the form in page1.php. Or only input data in the Name input field at the form in page1.php and leave the other iunput field of the form empty?

How that WHERE clause would look like ?

Help please…

build your where clause according to what’s been set

you had this in the other code, what happened to it?

If you want a query that kinda self adapts, you can do something like


$query4 = "
...
 WHERE
      (LENGTH('$strZipCode') = 0 OR zip = '$strZipCode')
      AND
      (LENGTH('$strState') = 0 OR state = '$strState')
      AND
      (LENGTH('$strName') = 0 OR name = '$strName')
";

Personally I’d go more for something like


$conditions = array();
if ($strZipCode) {
    $conditions[] = "zip = '$strZipCode'";
}
if ($strState) {
    $conditions[] = "state = '$strState'";
}
if ($strName) {
    $conditions[] = "name = '$strName'";
}

echo implode(' AND ', $conditions);

Be sure to count() the conditions to make sure you have at least one.

Either that, or append your base query with:-


WHERE 1 = 1

…this should allow you to throw on those conditionals a little bit easier. :wink:

hash I only had it to display if $strZipCode and was the only input field by the user. But it was not displaying if $strState was input along or, strName, or $strFoodTypes …

Ahi ahi !!

I tried as below


WHERE zip= '$strZipCode' OR name='$strName' OR state='$strState'";

it worked only for zip and name but for state won’t display the fields of the stores table I believe because it is an array?

Well…

I will try the two scripts above.

Thanks!