0

I make a PHP MySQL search, the custom may be type something like word or word1 word2 or word1 word2 word3... I need to get the final query like

$qry = "SELECT title,content,date 
FROM articles WHERE 
(title like '%$word1%' and title '%$word2%') 
OR 
(content like '%$word1%' and content title '%$word2%')"
OR
(title like '%$word1%' and content title '%$word2%')
OR
(title like '%$word2%' and content title '%$word1%'); // make sure custom type words all match in database column title and content, maybe only '%$word1%', or maybe multi words '%$word1%', '%$word2%', '%$word3%'...

I use some code below, but it could not reach my request. how to make it right? Thanks.

$qry = "SELECT title,content,date FROM articles";
if($_REQUEST['search']!=""){
    $searchText = $_REQUEST['search'];
    $words = preg_split("/\s+/",$searchText); 
    $uniqueWords = array_keys(array_flip($words)); 
    $parts = '';
    foreach($uniqueWords as $word){     
    $parts[] = " content like '%$word%' ";
    } 
    $where = implode(" AND ", $parts);
    foreach($uniqueWords as $word){     
    $parts[] = " title like '%$word%' ";
    } 
    $where1 = implode(" AND ", $parts);
    foreach($uniqueWords as $word){     
    $parts[] = " title like '%$word%' OR content like '%$word%' ";
    } 
    $where2 = implode(" AND ", $parts);
    $qry .=" WHERE $where OR $where1 OR $where2 Order By date DESC ";
}
4

1 Answer 1

2

I'm not sure exactly what you're after (are you wanting to match any keyword in title or contents or match both keywords to both columns...?) But what about something like this:

$keywords = explode(' ',mysql_real_escape_string($_REQUEST['search']));
$qry = "SELECT title,content,date FROM articles WHERE (";
$qry2 = '';
foreach($keywords as $n => $word)
{
    $qry2 .= " title LIKE '%$word%' OR content LIKE '%$word%' OR";
}
$qry .= trim($qry2, 'OR');
$qry .= ") ORDER BY title";

Not tested this, but it seems ok.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.