0

我有这个搜索代码:

<?php
//members
$sql="SELECT * from members WHERE ";
$sql.="forename LIKE '%".$_GET["s"]."%' OR ";
$sql.="surname LIKE '%".$_GET["s"]."%' ";
$rs=mysql_query($sql,$conn);
if(mysql_num_rows($rs) > 0)
{
    echo '<table width="100%" border="0" cellspacing="5" cellpadding="5">
      <tr>
      <td colspan="3"><h3>Members</h3></td>
      </tr>
      <tr>
        <td><strong>Member Name</strong></td>
        <td><strong>D.O.B</strong></td>
        <td><strong>Age</strong></td>
      </tr>';
    while($result=mysql_fetch_array($rs))
    {
        //work out the age of each member
        $sql2="SELECT TIMESTAMPDIFF(YEAR,CONCAT(dob_year, '-', dob_month, '-', dob_day),CURDATE()) as years, (TIMESTAMPDIFF(MONTH,CONCAT(dob_year, '-', dob_month, '-', dob_day),CURDATE()) - TIMESTAMPDIFF(YEAR,CONCAT(dob_year, '-', dob_month, '-', dob_day),CURDATE())*12) as months FROM members where sequence = '".$result["sequence"]."' ";
        $rs2=mysql_query($sql2,$conn);
        $result2=mysql_fetch_array($rs2);

        //date in mm/dd/yyyy format; or it can be in other formats as well
         $birthDate = "12/17/1983";
         //explode the date to get month, day and year
         $birthDate = explode("/", $birthDate);
         //get age from date or birthdate
         $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])-1):(date("Y")-$birthDate[2]));

         $forename = implode('<strong>'.$_GET['s'].'</strong>',explode($_GET['s'],$result['forename']));
         $surname = str_replace($_GET["s"], '<font color="#FF0000">'.$_GET["s"]."</font>", $result['surname']);
         echo '<tr class="notfirst" style="cursor:pointer;" onclick="document.location=\'/members/edit_member.php?seq='.$result["sequence"].'\'">
        <td> '.$forename.' '.$surname.'</td>
        <td>'.$result["dob_day"].' / '.$result["dob_month"].' / '.$result["dob_year"].'</td>
        <td>'.$result2["years"].' years / '.$result2["months"].' months</td>
      </tr>';
    }
    echo '</table>';
}
?>

我想在我的结果中突出显示搜索词

如您所见,我尝试使用以下方法来做到这一点:

$forename = implode('<strong>'.$_GET['s'].'</strong>',explode($_GET['s'],$result['forename']));

$surname = str_replace($_GET["s"], '<font color="#FF0000">'.$_GET["s"]."</font>", $result['surname']);

但它不起作用 - 实现这一目标的最佳方法是什么。我希望它适用于名字和姓氏结果

我尝试使用以下代码:在 mysql php 搜索中突出显示搜索文本

4

1 回答 1

0

然后首先修复sql注入问题。

$search = mysql_real_escape_string($_GET['s']);
$text = str_replace($search,"<b>$search</b>",$textFromMysqlResult); 
echo $text; 
于 2013-10-06T17:38:34.357 回答