$wpdb query not working in plugin

时间:2015-10-30 23:29:07

标签: wordpress

I'm trying to do a reviews plugin in Wordpress, and one of the thing that my client asked me to do was that a user should be able to rate only one product every 24 horas, so I have to establish a limit between rates. And I made this function to check if the limit is reached: function isAllowedToRate(){ global $wpdb; $currentDate = date('Y-m-d'); $userId = get_current_user_id(); $table_name = $wpdb->prefix .'esvn_reviews'; $isAllowed = $wpdb->get_results( " SELECT user_id, fecha_calificacion FROM {$table_name} WHERE user_id = {$userId} AND review_date = {$currentDate} " ); if( count( $isAllowed > 0 ) ){ return false; }else{ return true; } } But every time I try to run it, it returns false, the error that I'm getting from Wordpress is this: <div id='error'> <p class='wpdberror'><strong>WordPress database error:</strong> []<br /> <code> SELECT user_id, fecha_calificacion FROM wp_esvn_reviews WHERE user_id = 6 AND fecha_calificacion = 2015-10-30 </code></p> </div> If I take the same SQL and run it directly into the database, it works like a charm, but I keep getting this error from Wordpress and the function always returns false.

2 个答案:

答案 0 :(得分:0)

You need to wrap your date in single quotes. $isAllowed = $wpdb->get_results( " SELECT user_id, fecha_calificacion FROM {$table_name} WHERE user_id = {$userId} AND review_date = '{$currentDate}' " ); Alternatively you could use $wpdb->prepare(), which I would consider better form. $sql = <<<SQL SELECT user_id, fecha_calificacion FROM {$table_name} WHERE user_id = %d -- this is formatted as a (d)igit AND review_date = %s -- this is formatted as a (s)tring SQL; $isAllowed = $wpdb->get_results($wpdb->prepare($sql, $userId, $currentDate));

答案 1 :(得分:0)

我发现错误(如果将来有人需要这些信息),我将$ isAllowed视为一个数组,它是一个对象,我不得不将ARRAY_A添加到get_results:

$isAllowed = $wpdb->get_results( 
                "
                SELECT user_id, fecha_calificacion 
                FROM {$table_name}
                WHERE user_id = {$userId} 
                    AND review_date = {$currentDate}
                ",ARRAY_A /* output as an associative array */
            );