PHP / MySQL - 搜索查询

时间:2010-12-14 19:25:38

标签: php wordpress mysql

我需要帮助对评论进行搜索查询(这是针对WordPress网站的。)

以这种方式检索评论 - 如果用户已登录:

       $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d
       AND (comment_approved = '1' OR (user_id = %d AND comment_approved = '0'))
       ORDER BY comment_date_gmt", $post->ID, $user_ID));

如果不是:

       $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d
       AND (comment_approved = '1' OR (comment_author = %s
         AND comment_author_email = %s AND comment_approved = '0'))
       ORDER BY comment_date_gmt",
       $post->ID, wp_specialchars_decode($comment_author,ENT_QUOTES),
       $comment_author_email));

所以我如何过滤包含特定搜索字符串的注释,例如$_GET['search_query']

这是WP的database structure。我正在寻找的搜索字符串位于comment_content

3 个答案:

答案 0 :(得分:2)

使用LIKE

 $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_content LIKE ('%$_GET['search_query']%')
and comment_post_ID = %d
       AND (comment_approved = '1' OR (user_id = %d AND comment_approved = '0'))
       ORDER BY comment_date_gmt", $post->ID, $user_ID));

答案 1 :(得分:1)

您可以将它们全部放在数组中并使用array_search:

http://il2.php.net/manual/en/function.array-search.php

您还可以使用wp google搜索查询窗口小部件。我以前用过它 太棒了:

http://www.lautr.com/wp-google-search-query-widget-wordpress-plugin

答案 2 :(得分:1)

  谢谢,我会试试。顺便说一下,在$ _GET之前和之后百分号是做什么的?

它将匹配搜索字符串之前和之后的任意数量的字符。