0

Ok so I have been trawling Internet for hours trying to resolve this issue but I am still at a complete lost, so would very much welcome some help or point in the right direction.

I have a MySQL query where I calculate the average of a column which is all fine. It’s in displaying it is where I am having problems.

I've dumped the $results variable and it returns the following:

array(1) { [0]=> object(stdClass)#1826 (2) { ["page_id"]=> string(1) "5" ["avg(r_location)"]=> string(6) "4.0000" } } 

The error I get also from the echo $row... is:

Fatal error: Cannot use object of type stdClass as array

My code is below

function returnResults() {

    $postid = get_the_ID();

    global $wpdb;

    $results = $wpdb->get_results(" SELECT page_id, avg(r_location) FROM wp_ratings WHERE page_id = '$postid' ");

    var_dump($results);

    foreach ($results as $row) {
            echo $row['avg(r_location)'];

    }

}
0

2 Answers 2

1

Fatal error: Cannot use object of type stdClass as array

The error message is telling you everything. You are trying to use an object as an array.

Since the result is an array of objects and not arrays you will need to add an alias to your query like this:

$results = $wpdb->get_results("SELECT page_id, avg(r_location) average 
                               FROM wp_ratings 
                               WHERE page_id = '$postid'");

Then you can access each value:

foreach($results as $row) {
  echo $row->average;
}

Notice that get_results() takes a second parameter $output_type which controls the return value. To get a result of associative arrays you could add ARRAY_A as the second parameter:

$results = $wpdb->get_results("SELECT page_id, avg(r_location) average 
                               FROM wp_ratings 
                               WHERE page_id = '$postid'", ARRAY_A);

foreach($results as $row) {
  echo $row['average'];
}

In this case you are not really forced to add an alias. You could access the array as you did before echo $row['avg(r_location)'];

Sign up to request clarification or add additional context in comments.

Comments

0

First correct your query:

SELECT page_id, avg(r_location) as locat FROM wp_ratings WHERE page_id = '$postid'  

And then access it like this:

foreach($result as $row){
 $row->locat;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.