Trying to return count of database query. But, while the array has the right data, the return value is blank

function get_entry_count($pagename) {
    global $wpdb;
    $count = $wpdb->get_results("SELECT COUNT( * ) FROM wp_fpc_rg_lead_detail WHERE form_id =12 AND field_number =5 AND value =  '$pagename'" );
    return $count[0]->count;
    }

    $numofpeople = get_entry_count($post->post_title);
    echo "$numofpeople people filled out the form";

I’m trying to run the query above and output the number of records that match. If I add:

print_r($count);

above the return command, I get this:

Read More
Array ( [0] => stdClass Object ( [COUNT( * )] => 7 ) )

There ARE 7 records; and the returned value SHOULD BE 7.

But, the returned value ( $count[0]->count; ) seems to be null.. I’m sure it’s something stupid, but I just can’t get it to work.

Related posts

Leave a Reply

1 comment

  1. Try giving your COUNT(*) an alias in the query. Then you should be able to reference the alias as a property of the object. In the example below I have used lead_detail_count but feel free to change it to whatever you want.

    function get_entry_count($pagename) {
        global $wpdb;
        $count = $wpdb->get_results("SELECT COUNT( * ) as lead_detail_count FROM wp_fpc_rg_lead_detail WHERE form_id =12 AND field_number =5 AND value =  '$pagename'" );
        return $count[0]->lead_detail_count;
    }
    

    get_results can also take a 2nd parameter that will change the return value and may be worth taking a look at. The link to the codex is below.
    http://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results