douna2917 2015-05-20 14:05
浏览 78
已采纳

Wordpress:wpdb准备条件变量

I currently have a table. If the user searches for something, I would like the query to return the filtered results. If the user doesn't search for something, it should return all results. I'm not too sure how to do this with wpdb prepare.

if($search_query!=="all") {
    $search_query = '%' . $search_query . '%';
    $where = 'WHERE column_name LIKE %s';   
}

$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}table_name ".$where." ORDER BY id DESC LIMIT %d, %d", $search_query,$current_page,$rows_per_page));

Right now nothing returns when the search field is empty because the query is erroring out because it's throwing the parametrization off and passing $search_query to the %d beside LIMIT. Is it possible to make this variable conditional? Is there a way to do this without an IF statement ?

  • 写回答

3条回答 默认 最新

  • doz59484 2015-05-20 14:12
    关注

    Why not do the prepare in the "If" statement? You can then do the other prepare (without the where clause) in the "Else" and just use the get_results on the proper prepared query?

    if($search_query!=="all") {
        $search_query = '%' . $search_query . '%';
        $where = 'WHERE column_name LIKE %s'; 
        $prepared = $wpdb->prepare("SELECT * FROM {$wpdb->prefix}table_name ".$where." ORDER BY id DESC LIMIT %d, %d", $search_query, $current_page, $rows_per_page)  ;
    } else {
        $prepared = $wpdb->prepare("SELECT * FROM {$wpdb->prefix}table_name ORDER BY id DESC LIMIT %d, %d", $current_page, $rows_per_page);
    }
    $results = $wpdb->get_results($prepared);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?