Quote:
Originally Posted by Rakuli
- PHP: Select all
$search = $_POST['search']; // Fill the variable with search
// This is the first part of the where clause searching for the whole string
$where = " username LIKE %{$search}% OR firstname LIKE %{$search}% OR lastname LIKE %{$search}% ";
// Now we'll split that search term into an array by breaking it to pieces at spaces
$search = explode(' ', $search);
$nm = $search; // Count how many parts there are to the string
// If there was only one part then we won't get any more detailed than that
if ($nm > 1) { // So there's more than one part so we'll add the individual searches to the where clause foreach ($search as $s) $where .= " username LIKE %{$s}% OR firstname LIKE %{$}% OR lastname LIKE %{$s}% ";
}
// Now the whole query has been constructed so it's just a matter of getting the results now
$result = mysql_query("SELECT * FROM users WHERE $where");
// etc.....
|
Not a bad bit of code, but you can do it all in one little line:
- PHP: Select all
$where = substr(preg_replace("(\w+)", "OR (username LIKE '%$0%' OR firstname LIKE '%$0%' OR lastname LIKE '%$0%')", $_POST['search']), 3);
$result = mysql_query("SELECT * FROM users WHERE $where");
Use a regular expression to
a) find each word
b) replace it with " OR username LIKE ..."
c) use the substr function to ignore the first "OR "
...and this would work much better as a function you can use in different applications. Write something once and re-use it 'til the cows come home'