简体   繁体   中英

WPDB: count number of times a particular value appears

I am trying to count the number of times the value of "yes" appears in the column "helpful" in the table "wp_wthp_helpful_log" for the current post in the loop.

在此处输入图片说明

Here is what I have so far, but isn't working. Any guidance would be helpful. This is the first time I have ever tried to use 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 {  };
?>

Got it working with this...

<?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 {  };
?>

You have to put yes in quotes because it's a literal string, not a name that MySQL recognizes:

<?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 {  };
?>

Note also the { and } around $wpdb->wp_wthp_helpful_log .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM