jaw
jaw

Reputation: 153

Trouble getting query result to display

My query is working below, except I can't display the results which should be "2" (the results of the distinct count). 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>";

Upvotes: 4

Views: 46

Answers (1)

hjpotter92
hjpotter92

Reputation: 80629

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

  1. Store the index as a separate variable and then use it when printing.

    $t = "COUNT(DISTINCT writing.ID)";
    print "Total Authors:" .$authors[0]->$t . "<p>";
    
  2. Use an alias in the 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>";
    

Upvotes: 1

Related Questions