I currently have a search feature for a knowledge base that filters out an array of common words (a, able, about, etc) so that they are not sent in the query. Unfortunately, when someone searches just one of those common words it returns nothing (whereas when it's not filtered and queries I have code to return a "Sorry, no results found" and log that search in the database).
I need to do the same for the filtered words if they are searched and no results are found, but I'm not sure the best way to go about that. Below is filtered code.
//Defines common words to be striped.
$commonWords = array('a','able', etc)
//Strips common words from being included as a search term
$searchterm = preg_replace("/\b(".implode('|',$commonWords).")\b/i",'',$searchterm);
if(mysql_num_rows($result) == 0) {
echo "<img src=\"images/oops.png\"> Sorry, no results found. <br /><br /><div id=\"custformSubmit\">Chat Now</div>";
//Records missing search terms in a database
mysql_query("INSERT INTO quer (IP, Query) VALUES ('$ip','$sear开发者_开发技巧ch')") or die(mysql_error());;
I understand that if(mysql_num_rows($result) == 0) doesn't work because nothing is actually being searched on submit, but I'm not sure of the best way to fix that.
Edit: Also, the div id 'custformSubmit' brings up a chat window to chat with a representative which is necessary.
You should trim the string after it is filtered and check if(empty($filteredstring)) then don't do sql query and print message for nothing found.
Also it is quicker to use str_replace than preg if you don't have a complex pattern. You could set your common words as they keys of an array and the replacement ('') as the value then do something like str_replace(array_keys($filter), $filter, $string)
You could use preg_replace
's replacement counter (see documentation) and output Sorry, no results found.
if the number of replacements made == the number of words in the original query.
There might be a better way to do this, but that's what I can suggest with the code provided.
精彩评论