使用PHP搜索DataBase

时间:2014-04-24 11:07:16

标签: php

我试图在用户搜索数据库中的名称时显示以红色突出显示的找到的单词,这里是代码:

echo "<table class='nameList'>";
echo "<tr><h3>You have searched for <span class='red'>$query</span> ...Please find the details.</h3></tr>";
echo "<tr> <th >UN Number</th> <th>Full Name</th></tr>";    
      $result = mysql_query("SELECT UN,NAME FROM mytable WHERE (`NAME` LIKE '%".$query."%')") or die(mysql_error());
      if(mysql_num_rows($result) > 0){

          while($results = mysql_fetch_array($result)){

              echo "<tr><td>".$results['UN']."</td> <td>".$results['NAME']."</td></tr>";
         }

      }else{
          echo "<tr><td colspan='2'>Sorry..No results for <span class='red'>$query</span>, try again!</td><tr>";
            echo "</table>"; 

2 个答案:

答案 0 :(得分:0)

在使用Result

之前,您需要处理echo

当结果来自数据库时,您需要在结果中找到您的查询,并将其替换为具有红色样式或您想要的样式的跨度。在我使用background-color=yellow;的示例中,您可以将其更改为color=red;

    // Create a function that highlight a list of words in a string.
  function highlightWords($string, $words)
 {
    // foreach keyword as a word
    foreach ( $words as $word )
    {
        // find the word and replace it with background color = yellow , change it to red if you want.
        $string = str_ireplace($word, '<span style="background-color:yellow">'.$word.'</span>', $string);
    }

    // return the string
    return $string;
 }


// specify the words you are looking for
$words = array("Zebra");

// your string 
$string = "My Name Is Zebra will Zebra do this?";

// highlight it 
$string = highlightWords($string, $words);

// echo it
echo $string;

结果如下:

enter image description here

答案 1 :(得分:0)

while($results = mysql_fetch_array($result)){
    echo "<tr><td>".$results['UN']."</td> <td>".$results['NAME']."</td></tr>";
}

<td>

中使用样式

示例:

echo "<tr><td style='color:red'>".$results['UN']."</td> <td style='color:red'>".$results['NAME']."</td></tr>";