I am trying to create a search that searches for a few words. My first attempt did not produce any results and looks like this:
require_once('database_conn.php'); if($_POST){ $explodedSearch = explode (" ", $_POST['quickSearch']); foreach($explodedSearch as $search){ $query = "SELECT * FROM jobseeker WHERE forename like '%$search%' or surname like '%$search%' ORDER BY userID LIMIT 5"; $result = mysql_query($query); } while($userData=mysql_fetch_array($result)){ $forename=$userData['forename']; $surname=$userData['surname']; $profPic=$userData['profilePicture']; $location=$userData['location']; echo "<div class=\"result\"> <img class=\"quickImage\" src=\"" . $profPic. "\" width=\"45\" height=\"45\"/> <p class=\"quickName\">" . $forename . " " . $surname . "</p> <p class=\"quickLocation\"> " . $location . "</p> </div>"; } }
I also tried the following, which yielded results, but as you can imagine, I got duplicate results for every word I entered:
if($_POST){ $explodedSearch = explode (" ", $_POST['quickSearch']); foreach($explodedSearch as $search){ $query = "SELECT * FROM jobseeker WHERE forename like '%$search%' or surname like '%$search%' ORDER BY userID LIMIT 5"; $result .= mysql_query($query); while($userData=mysql_fetch_array($result)){ $forename=$userData['forename']; $surname=$userData['surname']; $profPic=$userData['profilePicture']; $location=$userData['location']; echo "<div class=\"result\"> <img class=\"quickImage\" src=\"" . $profPic. "\" width=\"45\" height=\"45\"/> <p class=\"quickName\">" . $forename . " " . $surname . "</p> <p class=\"quickLocation\"> " . $location . "</p> </div>"; } } }
I pretty much do not understand how to do this, any help would be greatly appreciated.
EDIT:
if($_POST){ $quickSearch = $_POST['quickSearch']; $explodedSearch = explode (" ", trim($quickSearch)); $queryArray = array(); foreach($explodedSearch as $search){ $term = mysql_real_escape_string($search); $queryArray[] = "forename like '%" . $term . "%' surname like '%" . $term . "%'"; } $implodedSearch = implode(' or ', $queryArray); $query="SELECT * FROM jobseeker WHERE ($implodedSearch) ORDER BY userID LIMIT 5"; $result = mysql_query($query); while($userData=mysql_fetch_array($result, MYSQL_ASSOC)){ $forename=$userData['forename']; $surname=$userData['surname']; $profPic=$userData['profilePicture']; $location=$userData['location']; echo "<div class=\"result\"> <img class=\"quickImage\" src=\"" . $profPic. "\" width=\"45\" height=\"45\"/> <p class=\"quickName\">" . $forename . " " . $surname . "</p> <p class=\"quickLocation\"> " . $location . "</p> </div>"; } }
source share