PHP/SQL Search Help

Hi there,

I’ve written the following code (with some help via online tutorials) to facilitate a “name finder” for a website I am developing. The user will search for a name, and the form will return results showing the name’s origin and meaning.

What I’m missing is the ability to narrow down the search by Gender. I want the users to be able to select whether they are searching for a Male name or a Female name. The “gender” field is in the same table.

So basically, I need the HTML form to have a drop down box with Male & Female as the options and whichever one is picked needs to be included in the search as the “gender” variable… I hope that makes sense.

Can someone help?

// Set up our error check and result check array
$error = array();
$results = array();

// First check if a form was submitted. 
// Since this is a search we will use $_GET
if (isset($_GET['search'])) {
   $searchTerms = trim($_GET['search']);
   $searchTerms = strip_tags($searchTerms); // remove any html/javascript.
   
   if (strlen($searchTerms) < 3) {
      $error[] = "Search terms must be longer than 3 characters.";
   }else {
      $searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection.
   }
   
   // If there are no errors, lets get the search going.
   if (count($error) < 1) {
      $searchSQL = "SELECT name, gender, meaning, origin FROM names WHERE ";
      
      // grab the search types.
      $types = array();
      $types[] = isset($_GET['name'])?"`name` LIKE '{$searchTermDB}'":'';
      $types[] = isset($_GET['gender'])?"`gender` LIKE '{$searchTermDB}'":'';
      
      $types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked)
      
      if (count($types) < 1)
         $types[] = "`name` LIKE '{$searchTermDB}'"; // use the name as a default search if none are checked
      
          $andOr = isset($_GET['matchall'])?'AND':'OR';
      $searchSQL .= implode(" {$andOr} ", $types) . " ORDER BY `name`"; // order by title.

      $searchResult = mysql_query($searchSQL) or trigger_error("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$searchSQL}");
      
      if (mysql_num_rows($searchResult) < 1) {
         $error[] = "The search term provided {$searchTerms} yielded no results.";
      }else {
         $results = array(); // the result array
         $i = 1;
         while ($row = mysql_fetch_assoc($searchResult)) {
            $results[] = "{$i}: Name: <span id=\\"result\\">{$row['name']}</span><br /> Gender: <span id=\\"result\\">{$row['gender']}</span><br /> Origin: <span id=\\"result\\">{$row['origin']}</span><br /> Meaning: <span id=\\"result\\">{$row['meaning']}</span><br /><br />"; $i++;
         }
      }
   }
}

function removeEmpty($var) {
   return (!empty($var)); 
}
?>
<html>
   <title>Name Finder</title>
   <style type="text/css">
      #error {
         color: red;
      }
	  #terms {
		  color: red;
		  text-decoration: underline;
		  font-weight: bold;
	  }
	  #result { 
	  color: blue;
	  font-weight: bold;
	  }
   </style>
   <body>
      <?php echo (count($error) > 0)?"The following had errors:<br /><span id=\\"error\\">" . implode("<br />", $error) . "</span><br /><br />":""; ?> <form method="GET" action="<?php echo $_SERVER['../../../PHP_SELF'];?>" name="searchForm"> <strong>Enter a name to find it's origin and meaning: </strong> <input type="text" name="search" value="<?php echo isset($searchTerms)?htmlspecialchars($searchTerms):''; ?>" /> <br /><br />
         <input type="submit" name="submit" value="Search!" />
      </form>
      <?php echo (count($results) > 0)?"You searched for: <span id=\\"terms\\">{$searchTerms}</span> - Here are your results:<br /><br />" . implode("", $results):""; ?>
   </body>
</html>

this shows how to create a select list.

you will need to add a name attribute to it like you did for the input text boxes.

Ok, I got that thanks.

But how do I code the php to match both fields?

The HTML Search Form is now as follows:

      <?php echo (count($error) > 0)?"The following had errors:<br /><span id=\\"error\\">" . implode("<br />", $error) . "</span><br /><br />":""; ?> <form method="GET" action="<?php echo $_SERVER['../../../PHP_SELF'];?>" name="searchForm"> <strong>Enter a name to find it's origin and meaning: </strong> <input type="text" name="search" value="<?php echo isset($searchTerms)?htmlspecialchars($searchTerms):''; ?>" /> <br />
      <strong>Select Gender:</strong> <SELECT name="gender">
      <option>Male</option>
      <option>Female</option>
      </SELECT>
      <br /><br />
         <input type="submit" name="submit" value="Search!" />
      </form>
      <?php echo (count($results) > 0)?"You searched for: <span id=\\"terms\\">{$searchTerms}</span> - Here are your results:<br /><br />" . implode("", $results):""; ?>

But it’s my PHP code that I need the help with…

I think it’s this bit that needs changing:

if (count($error) &lt; 1) {
      $searchSQL = "SELECT name, gender, meaning, origin FROM names WHERE ";
      
      // grab the search types.
      $types = array();
      $types[] = isset($_GET['name'])?"`name` LIKE '{$searchTermDB}'":'';
      $types[] = isset($_GET['gender'])?"`gender` LIKE '{$searchTermDB}'":'';

I need to tell the page to search for entries that match both the name+gender selected.

You need to process $_GET[‘gender’] into something like ‘searchGenderDB’ the same way you processed $_GET[‘search’] into ‘searchTermDB’.

Then you should end up a new variable which you cna parse into the query:


$types[] = isset($_GET['name'])?"`name` LIKE '{$searchTermDB}'":'';
$types[] = isset($_GET['gender'])?"`gender` = '{$searchGenderDB}'":''; 

Hi Immerse.

I did figure that bit out eventually but thanks for your help… I now have another problem that I hope somebody can help with - related to this same code.

At the end of it all, I got it working perfectly… I tested it on my local installation and everything is 100% fine… when I put it on my LIVE site, I get an error message:

“Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/xxxxxx/public_html/wp-content/plugins/php-execution-plugin/includes/class.php_execution.php(273) : eval()’d code on line 44”

I am using this on a wordpress site with a plugin that allows me to execute PHP coed in my posts & pages… as i said, it works perfectly on my local installation but when I put it on the live site, which is an exact copy… I get that error.

Why would it work on one but not the other… the code is exactly the same, the database is identical and the wordpress installation & plugin are exactly the same.

Did you copy the database tables over?

Try var_dump($searchResult) and var_dump($searchSQL)
to see if the query is OK and if it’s being executed properly.

It’s strange that the trigger_error isn’t being run if there is an error…

Hi, I’m not sure where I would put those lines “var_dump” etc… but I know the search query is ok for 2 reasons…

  1. It’s EXACTLY the same as my localhost environment. The tables are copied over and are identical on the live server & the php script is also identical. Even the database usernames and passwords are all the same on my localhost as they are on the live server.

  2. I have pasted the query into phpmyadmin and run it to see if it comes back with the results and it goes through fine.

For some reason, there’s something stopping it from working on the live server. It doesn’t return any results and just gives that num_row error.