I would love to search strings from database but i want it to order by relevance
I have picked up this example and is believed to work just fine.
Before search
- The quick brown dog jumped fox-like.
- The quick brown fox jumped over the lazy dog.
- The quick fox jumped over the Sears Tower.
After search
- The quick brown fox jumped over the lazy dog.
- The quick brown dog jumped fox-like.
- The quick fox jumped over the Sears Tower.
Code used
SELECT *
FROM `items`
WHERE `description` LIKE 'quick'
AND (
`description` LIKE 'brown'
OR `description` LIKE 'fox'
OR `description` LIKE 'lazy'
OR `description` LIKE 'dog'
)
LIMIT 0 , 30
ORDER BY (
(
CASE WHEN `description` LIKE 'brown'
THEN 1
ELSE 0
END
) + (
CASE WHEN `description` LIKE 'fox'
THEN 1
ELSE 0
END
) + (
CASE WHEN `description` LIKE 'lazy'
THEN 1
ELSE 0
END
) + (
CASE WHEN `description` LIKE 'dog'
THEN 1
ELSE 0
END
)
) DESC
My question is. When users do the search, the search terms are dynamic. How do i add a for each in between the order by For the search to work.
What i have tried but still i know it wont work. First I don't know how to implode the + sign
$sql .= " ORDER BY ";
foreach ($words as $word) {
$sql .= " ( CASE WHEN `pd.name` LIKE '%".$word."%'
THEN 1
ELSE 0
END) + ";
}
$sql .= " ASC";
This is an Opencart Search Query example.
The code below works but how do i make it dynamic
$sql .= " ORDER BY
( CASE WHEN pd.name like '%".$word1."%' THEN 1 ELSE 0 END)
+
( CASE WHEN pd.name like '%".$word2."%' THEN 1 ELSE 0 END) DESC";