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,'.','');
 
     
    