View Single Post
  #6 (permalink)  
Old Feb 3rd, 2008, 10:54
spinal007's Avatar
spinal007 spinal007 is offline
Moderator
Join Date: Mar 2004
Location: Good Ol'London
Age: 23
Posts: 1,650
Blog Entries: 1
Thanks: 0
Thanked 4 Times in 4 Posts
Re: Complicated database querys

Quote:
Originally Posted by Rakuli View Post
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'

Last edited by spinal007; Feb 3rd, 2008 at 11:00.
Reply With Quote