Search Form
Now we have the database connection setup we need to setup our actual form code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <html>
<title>My Simple Search Form</title>
<style type="text/css">
#error {
color: red;
}
</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">
Search For: <input type="text" name="search" value="<?php echo isset($searchTerms)?htmlspecialchars($searchTerms):''; ?>" /><br />
Search In:<br />
Body: <input type="checkbox" name="body" value="on" <?php echo isset($_GET['body'])?"checked":''; ?> /> |
Title: <input type="checkbox" name="title" value="on" <?php echo isset($_GET['title'])?"checked":''; ?> /> |
Description: <input type="checkbox" name="desc" value="on" <?php echo isset($_GET['desc'])?"checked":''; ?> /><br />
Match All Selected Fields? <input type="checkbox" name="matchall" value="on" <?php echo isset($_GET['matchall'])?"checked":''; ?><br /><br />
<input type="submit" name="submit" value="Search!" />
</form>
<?php echo (count($results) > 0)?"Your search term: {$searchTerms} returned:<br /><br />" . implode("", $results):""; ?>
</body>
</html> |
You will notice that this is a simple form, no formatting. The PHP is mixed in with it. If you do not know, the ? and : are ternary operators which act like a short If/else statement.
Example: (condition is true/false) (then ?) do this (else : ) do that.
If you want to read more on HTML Forms, google it. What we are doing with the form code is checking different variables. First off, we see if there was an error by counting the error array. (This part of the code comes later). If there was an error, show the error to the users so they can fix it. Next we have different variables being echo’d. The first simply points the form to the search page for submission. The next are items that were previously on the form if they contain values. Should be pretty straight forward.
Finally we check to see if the $results array has any items. If the results array does, then we will display those results to the user along with the search terms that were used to grab these results. So now you hopefully understand the form and why the code is how it is.

Hi I’m building a magazine database for my work and found this tutorial really helpful, is there any way you could add pagination to it and only show a few records at a time.
Hi there.
Thanks a lot for your effective search engine. I appreciate your hard work. I was wondering if you could tell me how i would hyper link the title, display only a portion of the contents and then click and follow link for more details of the content to a separate page. Just like google style please?
Thanks,