Background
Users on a website can give their profile 'keywords', each separated with ', '. For example:
green apples, bananas, red apples, pears
This is stored in the database as a string.
I have a livesearch page where users can search for users by keyword. On this search, the page suggests keywords as the user types. For example, a user may type:
apples
and the page will suggest
green apples
, red apples
.
Method
When the input is sent to keywordsearch.php
, the page searches the following:
$search_string_w = '%'.$search_string.'%';
$stmt = $dbh->prepare('SELECT `keywords` FROM `users` WHERE `keywords` LIKE ?');
$stmt->execute(array($search_string_w));
while($results = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result_array[] = $results;
}
This gets the row of the user who has the keyword. However, all I want to do is display each individual keyword as search suggestions, even if the keyword appears multiple times.
if (isset($result_array)) {
foreach ($result_array as $result) {
$keyw = explode(', ', $result['keywords']);
$keyk = array_search($search_string, $keyw);
Now, $keyw[$keyk]
will return a single keyword. So if the search is apples
, this will only return green apples
and not red apples
too.
Question
How can I alter this code so that it returns all occurrences of the searched term?