Search code examples
phpmysqlrating

Average Rating script


I have asked this once before but i didnt get a very clear answer.

I need to know how to make a rating script for a site. I have a form that submits a rating out of ten to mysql. How would you get the average rating to be displayed from the mysql column using php?

One person suggested having two tables; one for all the ratings, and one for the average rating of each page. Is there a simpler method than this?


Solution

  • You will want to store the rating for each time a page is ratd. because if you just store the average rating in one column, such as

    ratings (page_id, average_rating)
    

    It is not easy to determine:

    1. How many users rated
    2. Distribution of the ratings (how many voted 10, for example)

    And you cannot allow users to change their rating, because everything has been flatten into one row. You can do without the second table if you use the average function in MYSQL

    $result = mysql_query("SELECT AVG(rating) FROM ratings GROUP BY page_id WHERE page_id = '$pageid'");
    $rating_for_page = mysql_fetch_row($result);
    $rating = $rating_for_page[0];
    

    Notice that I am assuming each rating is stored as a seperate row