dongtan7639
dongtan7639
2017-02-28 18:41

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 douwu7563 4年前

    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

    点赞 评论 复制链接分享