I tried the code with the modifications, but now it's only working when it's one word search, when I put two words it gives me this warning:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/comtact/public_html/search.php on line 100
It seems the loop isn't working if the count value isn't 0
The substr_count seem to still count one words as 0 and two as 1. I tried replacing $count = substr_count($post,' '); with $count = substr_count($split,' '); it works but then I'm back at the problem of mysql only searching for the first word because the substr_count returns 0 no matter the number of words
There're was a few typos in the script...
Heres one that should work...
[PHP]// search all words like the input
// trim whitespace from the ends of user input
$post=trim($_POST['keyword']);
// add slashes to prevent sql injection
if (!get_magic_quotes_gpc()) {
$post = addslashes($post);
}
// return an error if there isnt a search, or its too short?
if (!$post || strlen($post) <= 2) {
// a two char or less word is probably too short
//show an error or show form etc.
die('error');
}
$split = explode(' ', $post); // if there is two or more words
$count = sizeof($split); // $split is an array of each word, so we take the size
// we already checked and there is at least one word in the search
// create query for first
$condition = "title LIKE '%$split[0]%' OR author LIKE '%$split[0]%' OR content LIKE '%$split[0]%'";
// append additional words to the query
if ($count > 1) {
for ($i=1;$i<$count;$i++)
{
$keyword = '%'.$split[$i].'%';
$condition .= " OR title LIKE '$keyword' OR author LIKE '$keyword' OR content LIKE '$keyword'";
}
}
// query db
$sql=mysql_query("SELECT * FROM stories WHERE $condition");
$num_results=mysql_num_rows($sql);
// view your mysql search query
//echo "SELECT * FROM stories WHERE $condition";[/PHP]
You should always make sure you add slashes to the user input
I usually use this function when adding user input into a mysql query:
[PHP]// safely escape intput to sql query
// if the string will be shown in html output, also use striptags or html_entities
function safeEscapeString($string)
{
if (get_magic_quotes_gpc()) {
return $string;
} elseif (mysql_real_escape_string()) {
return mysql_real_escape_string($string);
} elseif (mysql_escape_string()) {
return mysql_escape_string($string);
} else {
return addslashes($string);
}
}
[/PHP]
it safely checks the functions supported by your php version, and implements the 'best' one.
mysql_real_escape_string() uses mysql's C++ API so is preferred.