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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?