0

I have some code to count and sum the rating numbers of users in my database (wodpress) about my product to show the average rating to others but I see this error: "Notice: Undefined variable: sum".
I think this error will be occured when no rating number is in database.
How can I solve it, my friends?

$sql = $wpdb->prepare( "
            SELECT meta_value 
            FROM {$wpdb->prefix}commentmeta 
            INNER JOIN {$wpdb->prefix}comments ON {$wpdb->prefix}commentmeta.comment_id = {$wpdb->prefix}comments.comment_ID 
            WHERE comment_post_ID = %d AND meta_key = 'rating' AND meta_value IS NOT NULL AND meta_value <> '' ", get_the_ID() 
        );
        $results = $wpdb->get_results( $sql );

        foreach($results as $result){
            $rate = $result->meta_value;
            $sum +=$rate;
        }
        $res = $sum/max( 1, count($results) );
        $res = number_format((float)$res,2,'.','');
Sh.Dehnavi
  • 65
  • 2
  • 12

2 Answers2

1

I'm not familiar with wordpress, but maybe that helps you. If $result is 0, you would divide by 0, which would result in an error. So I would always ask first if this is not equal to 0. Furthermore, you can do that as well as count the entries directly in the db

$sql = $wpdb->prepare( "
    SELECT SUM(meta_value) as sum,
            COUNT(meta_value) as count
    FROM {$wpdb->prefix}commentmeta 
    INNER JOIN {$wpdb->prefix}comments ON {$wpdb->prefix}commentmeta.comment_id = {$wpdb->prefix}comments.comment_ID 
    WHERE comment_post_ID = %d AND meta_key = 'rating' AND meta_value IS NOT NULL AND meta_value <> '' ", get_the_ID() 
);
$results = $wpdb->get_results( $sql );

if($results->sum != 0 && $results->count != 0){
    $res = $results->sum/$results->count;
    $res = number_format((float)$res,2,'.','');
} else {
    $res = 0;
}
Interface
  • 312
  • 3
  • 16
0
 $sum = 0;
 $sql .... // rest of your code

Declare it first and then start using it. You are declaring it within the loop for the first time and accessing it out of the scope where it gets created.

In the older version of PHP it worked but in the newer versions, it will give this error.

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78