簡體   English   中英

PHP在MySQL中突出顯示搜索詞

[英]PHP highlight search terms in MySQL

我有這個搜索代碼:

<?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搜索中突出顯示搜索文本

首先修復sql注入問題。

$search = mysql_real_escape_string($_GET['s']);
$text = str_replace($search,"<b>$search</b>",$textFromMysqlResult); 
echo $text; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM