Failed to get query result for display

My query works below, except that I cannot display the results, which should be "2" (results of a separate account). Instead, I get "Total Authors: ID"

//var_dump Result:

array(1) {
[0]=> object(stdClass)#349 (1) {
["COUNT(DISTINCT writing.ID)"]=> string(1) "2″
}
}

//Code:

$authors = $wpdb->get_results("SELECT COUNT(DISTINCT writing.ID)
FROM writing
LEFT JOIN stories on writing.SID = stories.SID
LEFT JOIN wp_users ON writing.ID = wp_users.ID        
WHERE (stories.SID = $the_SID)"
);

echo var_dump($authors);
print "Total Authors:" .$authors[0]->writing.ID ."<p>";
+4
source share
1 answer

As you can see from the output var_dump, your required value is saved as a member of the COUNT(DISTINCT writing.ID)object. There are several workarounds that you can follow.

  • Save the index as a separate variable, and then use it when printing. A.

    $t = "COUNT(DISTINCT writing.ID)";
    print "Total Authors:" .$authors[0]->$t . "<p>";
    
  • Use an alias in your MySQL query.

    SELECT COUNT(DISTINCT writing.ID) AS writingID
    FROM writing
    LEFT JOIN stories ON writing.SID = stories.SID
    LEFT JOIN wp_users ON writing.ID = wp_users.ID        
    WHERE (stories.SID = $the_SID)
    

    and then

    print "Total Authors:" .$authors[0]->writingID . "<p>";
    
+1
source

All Articles