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 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用