WPDB:计算特定值出现的次数

时间:2015-09-28 21:11:16

标签: php wordpress wpdb

我正在尝试计算“wp_wthp_helpful_log”表中“有用”列中“是”的值出现在循环中当前帖子的次数。

enter image description here

这是我到目前为止所做的,但是没有用。任何指导都会有所帮助。这是我第一次尝试使用wpdb。

<?php
global $wpdb;
$helpfulcount = $wpdb->get_var(" SELECT COUNT(*) FROM {$wpdb->wp_wthp_helpful_log} WHERE post_id = $id AND helpful = 'yes' ");
if ( $helpfulcount > 0 ) {
    echo 'I got a count of '.$helpfulcount ;} else {  };
?>

搞定了......

<?php
global $wpdb;
global $post;
$postid = $post->ID;
$helpfulcount = $wpdb->get_var(" SELECT COUNT(*) FROM wp_wthp_helpful_log WHERE post_id = $postid AND helpful = 'yes' ");
if ( $helpfulcount > 0 ) {
echo 'I got a count of '.$helpfulcount ; } else {  };
?>

1 个答案:

答案 0 :(得分:0)

您必须将yes放在引号中,因为它是一个文字字符串,而不是MySQL识别的名称:

<?php
    $helpfulcount = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->wp_wthp_helpful_log} WHERE postid = $id AND helpful = 'yes'");
    if ( $helpfulcount > 0 ) {
        echo 'I got a count of '.$helpfulcount ; } else {  };
?>

还请注意{周围的}$wpdb->wp_wthp_helpful_log