0

My table looks like this

Id  | name   
---------------
1   |  clinker
2   |  gypsum

Now I need to prepare a search based on the 'name' field. here is the select statement

select * from table where name like '%$keyword%'

Now, suppose the keyword is 'clinker 1', and I want first row of my table as result set. How can I accomplish that?

JimmyB
  • 12,101
  • 2
  • 28
  • 44

2 Answers2

-1

You'll need to split the $keyword and expand your query to match any word in the $keyword list:

$keywordList = explode(' ', $keyword);
$sql = 'select * from table where ';
while (!empty($keywordList)) {
    $likeKeyword = array_shift($keywordList);
    $sql .= "keyword like '%{$likeKeyword}%'";
    if (!empty($keywordList))
        $sql .= " or ";
}
//...run your query here

So if the $keyword is clinker 1, the resulting query would be:

select * from table where keyword like '%clinker%' or keyword like '%1%'
Lucian D.
  • 95
  • 5
-1

Not quite sure about MySQL, but LIKE should work with any character expression on either or both sides. That includes both columns and literals. Hence, the LIKE can be used the other way around to find the inverse matches:

SELECT *
FROM table
WHERE name LIKE '%$keyword%'
OR '$keyword' LIKE CONCAT('%', name, '%')
JimmyB
  • 12,101
  • 2
  • 28
  • 44