unordered word search

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

   I've built a search engine that queries a MySQL database. However,
if I enter "foo bar", the engine will search for that phrase exactly,
and will not find "bar foo" nor "foo something bar". How do you
separate words so that the engine finds them individually? I'm thinking
something like

$tokenized = strtok($query, " ")
mysql_query(" SELECT ... FROM ...
while(...){ WHERE ...}

but I just can't figure it out. Any help is much appreciated. Many
thanks in advance.


Re: unordered word search wrote:

Quoted text here. Click to load it


Suppose you have a table with firstname and lastname and etc. etc., and you  
want to search firstname.
(I wrote an example in clear steps, so you see what happens. You can code it  
a lot more dense if you prefer that.)

$searchwords = "foo bar whatever etc";
$ARRsearch = explode(" ",$searchwords);

$SQL = "SELECT firstname, lastname, ..... FROM tblYouKnow WHERE (";

$SQL_wordsearch = array();

foreach($ARRsearch as $oneWord){
 $SQL_wordsearch[] = "(firstname LIKE '%".$oneWord."%')";

// add the pieces to SQL, use " OR " as 'glue':
$SQL .= implode(" OR ",$SQL_wordsearch);
$SQL .= ");";

echo $SQL;

// Now execute the SQL the way you are used to.

Good luck.

Erwin Moller

PS, I am using the LIKE with %. I am unsure if that is supported like that  
in mysql because I never use mysql. Maybe you need different syntax, but  
that is just SQL syntax, you'll figure that out.

Re: unordered word search wrote:

Quoted text here. Click to load it

if you wnat to search these words in this order you can simply do something
like this..
$string = "word0 word1  word2   word3    word4     ";
$words = '%' . preg_replace('/ +/', '%', trim($string)) . '%';
$words = mysql_escape_string($words);
echo "SELECT * FROM table WHERE nn LIKE '$words'";


Site Timeline