tags:

views:

113

answers:

4

I Keep getting the following error and I was wondering on how to fix it.

Fatal error: Unsupported operand types on line 97


Its around this area of code listed below. I can list the full code if needed.

PHP code

$total_rating_points = mysqli_fetch_array($result);
if (!empty($total_rating_points) && !empty($total_ratings)){
    $avg = (round($total_rating_points / $total_ratings,1));
    $votes = $total_ratings;
    echo $avg . "/10  (" . $votes . " votes cast)";
} else {
    echo '(no votes cast)';
}

Here is Line 97

$avg = (round($total_rating_points / $total_ratings,1));

Here is the full code.

function getRatingText(){
    $dbc = mysqli_connect ("localhost", "root", "", "sitename");

    $page = '3';

    $sql1 = "SELECT COUNT(*) 
             FROM articles_grades 
             WHERE users_articles_id = '$page'";

    $result = mysqli_query($dbc,$sql1);

    if (!mysqli_query($dbc, $sql1)) {
            print mysqli_error($dbc);
            return;
    }

    $total_ratings = mysqli_fetch_array($result);

    $sql2 = "SELECT COUNT(*) 
             FROM grades 
             JOIN articles_grades ON grades.id = articles_grades.grade_id
             WHERE articles_grades.users_articles_id = '$page'";

    $result = mysqli_query($dbc,$sql2);

    if (!mysqli_query($dbc, $sql2)) {
            print mysqli_error($dbc);
            return;
    }

    $total_rating_points = mysqli_fetch_array($result);
    if (!empty($total_rating_points) && !empty($total_ratings)){
        $avg = (round($total_rating_points / $total_ratings,1));
        $votes = $total_ratings;
        echo $avg . "/10  (" . $votes . " votes cast)";
    } else {
        echo '(no votes cast)';
    }
}
+6  A: 

$total_rating_points is an array. you cannot divide it by a number.

just somebody
how do I fix this because I need to divide $total_rating_points / $total_ratings
tEcHnUt
$total_ratings[0] / $total_rating_points[0]. You might also want to check if Count(*) is the correct aggregation function for both queries.
VolkerK
A: 
nickf
+2  A: 

(edited since the MySQL query was added to the question)

You've used mysql_fetch_array to get your result from MySQL, as the name suggests this returns an array. You can't do math like that on arrays.

You want to change your MySQL query to this:

$sql1 = "SELECT COUNT(*) as count
         FROM articles_grades 
         WHERE users_articles_id = '$page'";

Change your mysql_fetch_array code to this:

 $total_rating_points = mysql_result($result, 0, "count");

That will return the actual number, which you can then use for math. Change both of your queries to this format and you should be good to go.

SoapBox
+1 for reading between the lines here.
nickf
A: 

Use array_sum() on $total_rating_points and $total_ratings.

Alix Axel