我有这个搜索代码:
<?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']);
但它不起作用 - 这是实现这一目标的最佳方式。我希望它能同时使用姓名和姓氏结果
答案 0 :(得分:0)
首先修复sql注入问题。
$search = mysql_real_escape_string($_GET['s']);
$text = str_replace($search,"<b>$search</b>",$textFromMysqlResult);
echo $text;