Jump to content

Confused about constructing this simple query


Jeffro

Recommended Posts

$find is the search my user types in a form. 

 

In searching mysql I want to search inventory.title and inventory.description ... and I want to return all results that have $find in either the title or description. 

 

I tried this: 

select * from inventory WHERE title LIKE '%$find%' or description LIKE '%$find%'";

 

That works for single words but if the user types in 2 words, I need it to look in title and description for any combination. 

 

Example:  My user might type:  miami truck 

 

I need to then perform a search where miami might only be in the title and truck might only be in the description. 

You build the query dynamically.

 

$words=explode(' ', 'foo bar');

$query='SELECT * FROM inventory ';
$combine=' WHERE ';

foreach($words as $word)
{
    $query .= $combine . " ( title LIKE '%" . $word . "%' or description LIKE '%" . $word . "%' )";
    $combine=' AND ';
}

echo $query;

 

~awjudd

You build the query dynamically.

 

$words=explode(' ', 'foo bar');

$query='SELECT * FROM inventory ';
$combine=' WHERE ';

foreach($words as $word)
{
    $query .= $combine . " ( title LIKE '%" . $word . "%' or description LIKE '%" . $word . "%' )";
    $combine=' AND ';
}

echo $query;

 

~awjudd

 

Glad you hooked me up with that because I had to study it about 10 minutes to figure out what you were doing!  It finally made sense and I stuck it in my script.. and voila!  Works perfectly.  Thanks so much.  Really appreciate it. 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.