Displaying average rating

Here is the first part of basic rating script.
disp.php
Here we just collect the rating and number of votes given from the two fields ( rating, nov ) from the table content_rating. We will be displaying the average value of the ratings given so we will divide total rating by number of votes. To give a better output we will format the result to two decimal places. You can change this formatting as per your requirement. Here is the code to display the average rating
$disp_result=mysql_query("SELECT rating,nov FROM content_rating WHERE content_rating.cont_id= $cont_id");
$disp_row=mysql_fetch_object($disp_result);
if($disp_row){

$score_avg=number_format(($disp_row->rating/$disp_row->nov),2,".","");

echo "Average ratting:$score_avg : ";
After formatting we can display the value but we will try little more. We will display images in terms of number of stars showing the average rating the content got. For example we will display 2 full starts and 3 half stars to represent a rating of 2.34 within a scale of 1 to 5. We have two start images one showing full star and other showing half star. Here after rounding the average score to nearest integer we will be using one for loop to display full star images, then from that value of $i we will be displaying half star images till 5. Here is the code to do that .
$rt=round($score_avg);
$img="";
$i=1;
while($i<=$rt){
$img=$img."<img src=images/star.gif >";
$i=$i+1;
}
while($i<=5){
$img=$img."<img src=images/star2.gif >";
$i=$i+1;
}
echo $img;
}
The above code can be modified to get formatted average value from MySQL table itself and there is no need to format in php side. You can read the details on MySQL data format here. The modified code is given here. Note that you can use any one of them for your displaying the ratings.
$disp_result=mysql_query("SELECT format((rating/nov),0) as score_avg FROM content_rating WHERE content_rating.cont_id= $cont_id");
$disp_row=mysql_fetch_object($disp_result);
if($disp_row){

echo "Average ratting:$disp_row->score_avg : ";
$img="";
$i=1;
while($i<=$disp_row->score_avg){
$img=$img."<img src=images/star.gif >";
$i=$i+1;
}
while($i<=5){
$img=$img."<img src=images/star2.gif >";
$i=$i+1;
}
echo $img;
}
That is the end of our rating script. We can add more features like flood interval, IP checking etc to the script.


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com




    Post your comments , suggestion , error , requirements etc here .




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2023 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer