Hi all,
Well I thought what I was after was somewhat simple.
I have a search that returns the results no worries... but the non complex examples I look at for hightlighting words never include the search query so am not sure if I'm on the right track.
My end result is to have people type something in in the feild, then for the results to display as:
<a href"...?productid=$ID..>Field1 Field2</a>
Field3 (description)
Repeat as necessary...
I have the following search code which is working fine, displaying a simple result at the moment. I just need to change the query so it searchs all the fields rather then just description.
PHP Code:
$searchsmall=mysql_real_escape_string($_POST['searchsmall']);
//If they did not enter a search term we give them an error
if ($searchsmall == "")
{
echo "<p>You forgot to enter a search term.";
exit;
}
// We preform a bit of filtering
$searchsmall = strtoupper($searchsmall);
$searchsmall = strip_tags($searchsmall);
$searchsmall = trim ($searchsmall);
$sql = ("SELECT ID, Part, Name, Name2 FROM product WHERE Description LIKE '%".$searchsmall."%'");
$query = mysql_query($sql);
//And we display the results
while($result = mysql_fetch_array($query))
{
echo $result['Part'];
echo " ";
echo $result['Name'];
echo "<br>";
echo $result['Name2'];
echo "<br>";
echo "<br>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($query);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
Here is the example I found to highlight the searched word/s from the results.... how do i fit it in?
PHP Code:
/**
* @highlight words
* @param string $text
* @param array $words
* @param array $colors
* @return string
*/
function highlightWords($text, $words, $colors=null)
{
if(is_null($colors) || !is_array($colors))
{
$colors = array('yellow', 'pink', 'green');
}
$i = 0;
/*** the maximum key number ***/
$num_colors = max(array_keys($colors));
/*** loop of the array of words ***/
foreach ($words as $word)
{
/*** quote the text for regex ***/
$word = preg_quote($word);
/*** highlight the words ***/
$text = preg_replace("/\b($word)\b/i", '<span class="highlight_'.$colors[$i].'">\1</span>', $text);
if($i==$num_colors){ $i = 0; } else { $i++; }
}
/*** return the text ***/
return $text;
}
/*** example usage ***/
$string = 'This text will highlight PHP and SQL and sql but not PHPRO or MySQL or sqlite';
$words = array('php', 'sql', 'phpro', 'sqlite');
$string = highlightWords($string, $words);