DB Search: Multiple Columns

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
User avatar
Pyrite
Forum Regular
Posts: 769
Joined: Tue Sep 23, 2003 11:07 pm
Location: The Republic of Texas
Contact:

DB Search: Multiple Columns

Post by Pyrite »

This sniplet function, given a query of words from a form, generates the SQL needed to search for multiple words in multiple columns of a table.

Code: Select all

// Inputs: Single/Multiple Word Search
// Output: Returns SQL Query
function big_search($query) {
	$query_array = explode(" ", $query);
	$count = count($query_array);
	$sql = "SELECT pmpUserID, pmpFirstName, pmpLastName, pmpNickName FROM pmp_people WHERE ";
	for ($i=0; $i<$count; $i++) {
		$words = $query_array[$i];
		$sql .= "(pmpFirstName LIKE '%$words%' OR pmpNickName LIKE '%$words%' OR pmpLastName LIKE '%$words%' OR pmpDescription LIKE '%$words%') ";
		($i < $count-1) ? $sql .= "OR " : "";
	}
	$sql .= "ORDER BY pmpLastName";
	return $sql;
}
Post Reply