简体   繁体   中英

Averaging through sql query and php

I am trying to average a couple rows in mysql with php mysql_query but I seem to be having some issues..

    $ratingsql = "SELECT AVG(Rating) AS RatingAverage FROM wp_reciperatings;";
    $ratingresult = mysql_query($ratingsql);
    // Print out result
    while($ratingrow = mysql_fetch_array($ratingresult)){
        echo "The average rating is ".$ratingrow['AVG(RatingAverage)'];
        echo "<br />";

My table looks like..

          ID           Rating
        _______________________
        |  1      |        1  |
        |  1      |        2  |
        |  1      |        5  |

The ratings go from 1-5, 5 being best. I am able to punch in that mysql query into my sql client and it works fine, how come it doesnt work on my page?

Also, how do I calculate the average of just ONE id?

Thanks a lot guys! Much appreciated.

Change this -

echo "The average price of  is ".$ratingrow['AVG(rating)'];

to this -

echo "The average price of  is ".$ratingrow['RatingAverage '];

Since you're giving the result column an alias you need to use that alias in PHP to display the data.

The query for the average of one ID would be this -

SELECT AVG(Rating) AS RatingAverage 
FROM wp_reciperatings
WHERE ID = '1'; // replacing with ID as needed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM