Database Search Form

This is a way to search a database table for specific terms provided in a search form. We will start with the HTML form that uses GET to put the terms into a query string.

                                <form action="search.php" method="GET" class="searchform">
	<input type="text" name="terms" id="terms" />
	<input type="submit" class="submit" id="search" name="search" value="Search"/>
</form>
                            

We can now retrieve the terms from the query string and iterate through each one using a foreach loop to search each field in the database table for the presence of any entered terms.

                                //proper data must be on querystring
if(isset($_GET['search'])){
	 $terms = $_GET['terms'];
}else{
	header("Location: http://www.example.com/list.php");
}

$headline = "Search Results For:";
$terms = explode(" ", $terms);
$sql = "SELECT fieldID, fieldName, fieldImage, fieldDescription, fieldContent FROM Table";

foreach($terms as $term){
	$sql .=" AND (fieldName LIKE '%{$term}%' 
		OR fieldDescription LIKE '%{$term}%'
		OR fieldContent LIKE '%{$term}%')"
	;
}
$sql .= " ORDER BY fieldName ASC";
$searchTerms = implode(" ", $terms);

//store search query string in session variable to pass to view page
session_start();
$_SESSION['search'] = '&terms=' . implode("+", $terms) . '&search=Search';

// connection comes first in mysqli (improved) function
$result = mysqli_query(IDB::conn(),$sql) or die(trigger_error(mysqli_error(IDB::conn()), E_USER_ERROR));