doucan4873 2017-03-30 13:40
浏览 62
已采纳

$ wpdb返回空,包含日期选择

I'm working on a WordPress calendar plugin, with possibility to add events attached to one date. Events are stored in a custom database that works fine.

But I've got troubles with a function in wich I use a '$wpdb->get_results' This function need a date as parameter. This is my code :

function get_events_list($day) {

    global $wpdb
    $table = $wpdb->prefix . "mytable";

    $events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = $day)", ARRAY_A );

    var_dump($events_list);

}

'var_dump($events_list)' returns an empty array, but I've got entries in the table.

I tried the function with no paramater, entering a well-formated date directly in the sql request, like that :

function get_events_list() {
    $events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = '2017-03-30')", ARRAY_A );
}

This works great.

I also did a 'var_dump($wpdb->last_query)', trying to find what happen.

Tested with no parameter (hard-coded '2017-03-30'), wich is working fine, the last_query returns :

'SELECT * FROM wp_mytable WHERE date = '2017-03-30')'

With dynamic paramater, it returns the date without quote :

'SELECT * FROM wp_mytable WHERE date = 2017-03-30)'

I think I'm pointing the problem but cannot resolve it (I tried a lot of things). Could Someone help me please ? Thank you :)

  • 写回答

2条回答 默认 最新

  • duanan2732 2017-03-30 14:42
    关注

    Hello_ mate,

    first I dont't understand how could this ('SELECT * FROM wp_mytable WHERE date = '2017-03-30')') query work, this final bracket looks very very strange to me :).

    Anyway if your query is working fine then simply change:

    $events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = $day)", ARRAY_A );
    

    to

    $events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = '$day')", ARRAY_A );
    

    as you see we only put quotes when passing the variable.

    Let me know if this works for you.

    Good Luck!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?