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. 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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. 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.