dongtan7639 2017-02-28 18:41
浏览 44
已采纳

Wordpress MySQL查询结果 - 如何突出显示在显示表中的字符串

I have created a functioning WordPress page with two search boxes (and a pair of and/or buttons between them) that queries an sql database and returns a two-column table with rows that contain one (or both, as the case may be) of the searched-for strings ($search and $search2) and then paginates when results exceed 100 rows. I have tried three different methods of highlighting these strings in the table but can't get it to work. So I'd much appreciate some help. The relevant portion of the php code (for which I am using the WordPress Insert PHP plug-in) is:

[insert_php]

* * * * 

if ($andor == "and"){
$result = mysql_query("SELECT DATE(start_date), EVENT FROM {$table} WHERE EVENT REGEXP '$search'  >0 AND EVENT REGEXP '$search2' >0 LIMIT {$limits}");
}
else{
$result = mysql_query("SELECT DATE(start_date), EVENT FROM {$table} WHERE EVENT REGEXP '$search'  >0 OR EVENT REGEXP '$search2' >0 LIMIT {$limits}");
}
 * * * *
while($row = mysql_fetch_row($result))
{
    echo "<tr>";
    foreach($row as $cell)
    echo "<td>$cell</td>";
    echo "</tr>
";
}

[/insert_php]

First, I added a function to the functions.php file and tried calling it and couldn't make it work

function highlight_word( $content, $word) {
    $replace = '<span style="background-color: #FF0;">' . $word . '</span>'; 
    $content = str_replace( $word, $replace, $content ); 
    return $content; 
};

Then I tried a string replacement in a separate while loop. Finally I tried changing the existing while loop as follows:

while($row = mysql_fetch_row($result))
{
    echo "<tr>";
    foreach($row as $cell)
    echo "<td>" . str_replace($search, '<span style="background-color: #FF0;">' . $search . '</span>', $cell) . "</td>";
    echo "</tr>
";
}

It would be helpful if I could limit the highlighting to the second column("EVENTS") only, but this is much less important than simply getting it to work. And, yes, I will upgrade code to mysqli and escape query strings before finalizing. As always, thanks to all in this great community.

  • 写回答

1条回答 默认 最新

  • douwu7563 2017-03-01 12:35
    关注

    Why won't you use some highlight js library?

    mark.js supports highlighting in tables out of the box

    $("table tr td:nth-child(1)").mark('keyword');
    

    Check this example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗