displaying search results of more than one word
Posted
by fusion
on Stack Overflow
See other posts from Stack Overflow
or by fusion
Published on 2010-05-01T20:34:24Z
Indexed on
2010/05/01
20:47 UTC
Read the original article
Hit count: 167
in my search form, if the user types 'good', it displays all the results which contain the keyword 'good'. however if the user types in 'good sweetest', it displays no results because there is no record with the two words appearing together; BUT appearing in an entry at different places.
for example, the record says:
A good action is an ever-remaining store and a pure yield
the user types in 'good', it will show up this record, but if the user types in 'good' + 'pure', it will not show anything. or if the record contains the keyword 'good-deeds' and if the user types in 'good deeds' without the hyphen, it will not show anything.
what i would like is that if the user types in 'good' + 'pure' or 'good deeds' it should records containing these keywords highlighting them.
search.php code:
$search_result = "";
$search_result = $_POST["q"];
$search_result = trim($search_result);
//Check if the string is empty
if ($search_result == "") {
echo "<p class='error'>Search Error. Please Enter Your Search Query.</p>" ;
exit();
}
if ($search_result == "%" || $search_result == "_" || $search_result == "+" ) {
echo "<p class='error1'>Search Error. Please Enter a Valid Search Query.</p>" ;
exit();
}
$result = mysql_query('SELECT cQuotes, vAuthor, cArabic, vReference FROM thquotes WHERE cQuotes LIKE "%' . mysql_real_escape_string($search_result) .'%" ORDER BY idQuotes DESC', $conn)
or die ('Error: '.mysql_error());
function h($s) {
echo htmlspecialchars($s, ENT_QUOTES);
}
function highlightWords($string, $word)
{
$string = preg_replace("/".preg_quote($word, "/")."/i", "<span class='highlight'>$0</span>", $string);
/*** return the highlighted string ***/
return $string;
}
?>
<div class="caption">Search Results</div>
<div class="center_div">
<table>
<?php while ($row= mysql_fetch_array($result, MYSQL_ASSOC)) {
$cQuote = highlightWords(htmlspecialchars($row['cQuotes']), $search_result);
?>
<tr>
<td style="text-align:right; font-size:18px;"><?php h($row['cArabic']); ?></td>
<td style="font-size:16px;"><?php echo $cQuote; ?></td>
<td style="font-size:12px;"><?php h($row['vAuthor']); ?></td>
<td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']); ?></td>
</tr>
<?php } ?>
</table>
</div>
search.html:
<form name="myform" class="wrapper">
<input type="text" name="q" onkeyup="showUser()" class="txt_search"/>
<input type="button" name="button" onclick="showUser()" class="button"/>
<p>
<div id="txtHint"></div>
</form>
© Stack Overflow or respective owner