Creating 5 Star Rating System with PHP , MySQL ,Jquery and Ajax

Rating system is very useful to know what a user is liking most.In this tutorial you will learn about creating 5 Star Rating System with PHP,MySQL ,Jquery and Ajax.This tutorial also reduce chances of multiple votes by single user for same product.To prevent  multiple votes it will store user’s IP address and also set a cookie in user’s browser .It will check user’s IP address and cookies before inserting any vote into database.

Creating 5 Star Rating System with PHP , MySQL ,Jquery and Ajax

Creating 5 Star Rating System with PHP , MySQL ,Jquery and Ajax

If you do not want to read the entire tutorial for Creating 5 Star Rating System with PHP , MySQL ,Jquery and Ajax then follow these steps-

I)-Download the source (link is available at the end of tutorial).

II)-Extract the folder and open settings.php.

III)-Replace values of  $host,$uname,$pass and $rating_dbname with your own database host,user name,password and name.

IV)-Upload all files to your server.

V)-Open PHPMyAdmin and import ratings.sql.

Open rating.php by your browser if everything is fine it would work.

Here is the complete guide for creating 5 Star Rating System with PHP , MySQL ,Jquery and Ajax-

1.Create a rating widget using HTML-This is the source of PHP file which will show current ratings and allow a user to rate a particular code .Although this script is incomplete but at the end of the tutorial  i will update this file with few PHP code which will retrieve current ratings .Save this file as showrating.php .

2).Create a style sheet for ratings-This CSS file defines the positions and colors of rating widget you can customize it according to your need.There are three images of star which is used for rating-

I-star_blank.png-It is the default star.

II-star_overs.png-This is mouse over image which will display at the time of mouse over on any star.

III-star_blank.png-This image will show the current rating of product.

Save the given codes  as rating.css.

3). Java Script to handle events Java Script codes will handle the CSS classes of rating widget and it will  sent the ajax request to save rating of users into database.

4).Settings for MySQL database- This page stores the host,database name ,user name, password and rating table name in variables.This page also contain a function for connecting MySQL database.To use this script you must need to change $host,$uname,$pass and $rating_dbname.

 5).Create table for ratings-Now you need a table for storing ratings.You can import ratings.sql (which is available in source)  from PHPMyAdmin or manually create a table name ratings with columns id,total_votes,total_value and used_ips.

6).PHP Script to save ratings into MySQL database-When a user clicks on any star an AJAX request is send to this page .This page validate the rating of user and saves his rating into database.

7).Retrieve Ratings from MySQL Database-This page retrieves the ratings from  MySQL Database and display them into form of stars.The output of this page  is showratings.php which is used in first step to make this tutorial clear.There is no use of file showratings.php.

Now your  5 Star Rating System with PHP , MySQL ,Jquery and Ajax is ready you can see the demo and download the complete source from given links.

View Demo  Download Source

Common Errors and Solutions-


Notice: Undefined variable: rat in C:\xampp\htdocs\rating\rating.php on line 37

Notice: Undefined variable: v in C:\xampp\htdocs\rating\rating.php on line 41

Solution:Add this line at beginning of  rating.php.

2-Votes are not saving.

Solution:Try in a different browser with a different IP(or delete manually your votes from table).If problem still persist then print the query of line 40 (ratings.php) and run it from PHPmyAdmin to find out actual problem.


View Demo  Download Source

Incoming Search Terms:

  • 5StarRatingSystemwithPHP MySQL JqueryandAjax
  • javascript-mysql rating system code download
  • query to insert rating and review in videos in php
  • Jwill

    the sql file is not in the source file

  • engrmudasirmalik

    But what if i have to use this with CodeIgniter?
    Any suggestions?

    • Sorry ,but I have never tried it with CodeIgniter.

      • engrmudasirmalik

        Well thanks for response 🙂

  • Most of the time you get views on a post and you get small comments, i know how it feels because i myself am a retired blogger. I went in for the experience and i will return once i am good.

    But you sir? You website is MORE then useful. You have life-saved my life alot.
    Please do better SEO to get more discovered!

    Consider me an official and returning fan of your website.
    Please keep up the good work and thank you alot.

    I mean it!

    Thank you.

    • Guest

      this is a very good tutorial but i think i can have concern on the way the ip address is recorded in database i mean correct me if im wrong you are saving clients ip address in array and then save this array in database. so talking about thousands of visitors who rates the same product….. and ip array value grows gradually which could reach the maximum lenght of datatype…. anyway i might consider text datatype for this. anyway nice tutorial i like though.

      • Thanks for comment.

        I am using longtext for storing IP addresses,which can hold 4 GB data.Using this data type you can store more than 28000000 ratings for same product which is more than enough for any website.

  • ollie

    Amazing, going to try this tonight. Thanks Amit !!

  • ollie

    Im not sure exactly what values to change in the settings.php folder ? when i go to vote on a “star” i get the error Origin null is not allowed by Access-Control-Allow-Origin.

    Can anyone help ?

    • In settings.php you need to change the value of $rating_dbname ,$host,
      $uname,$pass with your database name ,database host (mostly localhost),database user name and data base password respectively .
      You are getting Origin null error because you are opening that page using URL
      file://……/rating.html instead of that use…./rating.html and make sure that XAMPP or WAMPP is running.

  • Ajay

    Thanks Alot Sir,

    Nice script, please use better seo for your site.

    I am really appreciate with this script, and forced to share your work on my blog.

    You are genius, Keep it up..!!

  • Sanjeev

    Nyc ,supreb

    How to show float point rating,like if average is 3.5 then it should be show 3 full voted and one half rated star ..?
    Is this possible to do with that script.?

    • You can change the width of each star depending on its rating .For example you can use
      3 star of 100% width and 1 star of 50% width but you have to mess with css and HTML.

  • Hey’
    Nice script really helpfull but i get this probleme :
    Warning: Division by zero in … line 198 :

    Can you help me please?

    • You can replace that line with given code


      else $rat=0;

  • Frode W

    Very nice script, Amit 🙂
    I had it working on the first attempt.

    Now, I’ve got hundreds of pages that I would like to add this nice rating script.
    Question is how to keep all the ratings apart.
    But where do I enter ID’s in your codes?

    The database should have an unique ID for each page, right?
    I can manually add new rows in my DB and name them ( 2,3,4,5,6…etc).

    • Frode W

      Never Mind.
      I changed this part of your code: “$ids=array(1,2,3);
      Into: “$ids=array(1-1000);

      Then I changed this code accordingly: “<div id="rating_1" class="ratings"
      Into: "rating_4 , rating_5 , rating_6…"…etc.

      Works smooth as guacamole 🙂

    • Yes,you need to assign a unique ID to each page.See line 4 of rating.php ,you can fill array $ids with your desired ids for which you need to show ratings.

  • ani

    nice script……. but its not working

    • Working demo is here -

  • ani

    plz help…

    • If you are getting any error then at least comment the error message or at least give the more detail about problem .Without any detail It’s not possible for me to help you.

      • ani

        its not getting insert into the database

        • Have you imported “ratings” table?

          • ani


          • Ping me on gtalk .I will try to figure out.

          • ani

            gtalk is not accessible in our company

          • Ok answer these questions-
            1.Are you able to see ratings?
            2.Make sure you have changed setting.php correctly.
            3.Provide me the link if you are not trying this script on localhost.

          • ani

            ya i can see da ratings…. when i select the ratings it will show Rating: 0.0/5 ( votes cast)
            Already voted for this item

            i hav changed in setting.php to my username and password and database
            m doing in localhost only…..
            thanks for ur support

          • ok replace this line

            mysql_query(“insert into ratings (id,date) values ($id_sent,curdate())”);
            $res=mysql_query(“insert into ratings (id,date) values ($id_sent,curdate())”);

            if(!$res)echo mysql_error();
            after this you able see the error message.

            Try to run this code in a different browser because it allow only one time to rate.

          • ani

            i got like this Field ‘used_ips’ doesn’t have a default value

          • Although this field doesn’t require a default value but you can use this as a default value

  • Eric Rohloff

    Cool Script. Here’s a replacement for the $ids=array(1,2,3); to set them dynamically.
    This is a mysql query to get the id array set from an outside database.

    if (mysqli_connect_errno())
    echo “Failed to connect to MySQL: ” . mysqli_connect_error();
    $query = “SELECT id FROM table_name”;
    $result = mysql_query($query);
    $ids = array();
    while ($row = mysql_fetch_assoc($result)){
    $ids[] = $row[‘id’];

    • Thanks! for sharing your codes.

    • Ahmed

      getting an error

      mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /home/content/75/11751475/html/rating/rating.php on line 12

      can email the file to me at

      • Make sure you have imported all tables and database username, password are correct.

        • arjun

          i would like to add ratings container individually so that i can give every id a different links so what should i do … please help

          • rajesh

            Yes, i need too, please help!

          • Pass a single value in $ids arrays.

          • rajesh

            i mean to say multiple ratings on the same page but different containers so that i can link every container a specific link
            please help…

          • rajesh

            please reply
            help me…!!

          • Ping me on Gtalk.

          • Wasey

            hey amit singh thank for the wonderful script.

            i too have the same problem what rajesh is asking “multiple ratings on the same page but different containers so that i can link every container a specific link”

            can you help me on my mail

          • Wasey

            please sir, i need it urgent can you please…

          • I have sent a request on gtalk,add me there.

  • Eric Rohloff

    I started putting together my html for integration of your script and found there was a closing divide tag missing and it wouldn’t validate. I added another closing divide tag down at the bottom right after thevote(s) cast) I tried to post the example code but the closing tag wouldn’t show.

    • I have added the missing tag.

      if you want to post any code in comment section then write your code in following format –


      Your code here


      but still Disqus Comments have many bugs so it may not work for you.

  • Favio

    Hi! Thanks for the code, is working, but I have an error. How to show the results? I cant see them until I vote. Thanks again.

    • Amit Singh

      You can see the results without voting.Read 7th point to know how to show results.

    • You can see results without voting.For how to see results ,see 7th point.

  • Ekrem Mert

    Guys please help me!

    Everything is working, but when i click on a rating, it doesnt save it on my MySql database. I see the id and date, but total_votes, total_value are jsut 0 all the time no matter what i vote. And the used_IP is empty! I have reset everything and uploaded and just editted the settings.php, but still same problem WHAT IS IT HELP ME PLEASE!!!!!!

    • Ekrem Mert


      • Amit Singh

        Echo the insert query then run that query from phpmyadmin you will able to find out error.

      • Echo the insert query then run that query from phpmyadmin you will able to find out error.

  • BobbyS

    Hi, do you know how to add three ratings at several place in a same page ? Please it’s very important ! Thanks !

    • See the demo, there is already three ratings.

  • Ricco Anggara

    im not understand .. -_-

  • Ricco Anggara


    • Please explain what are you trying and what problems are you facing ?

  • Pankaj

    Need help too.

    I downloaded the demo, setup the local database as per instructions… but not getting anything in the database.

    Console log says: no element found at end of rate.php file.

    Could somebody please help. Thanks!

  • সৌমেন দাশ গুপ্ত

    it’s functionable but if I use it for diffrent products or various products what can I do??? because it’s always giving me one rating for various items in my database…

    • You need to assign the different IDs for each product and then pass the IDs in $ids array mentioned in step 7.

      • সৌমেন দাশ গুপ্ত

        do I need to assign the different ids in rate.php ??

  • name


  • Bibash Shah

    Thanks for the nice tutorial. This is very helpful for me.
    But I have some thing that I have not understood. Hope you will bother to help me.

    I am working with my project I found this tutorial to add in it. I have already product table in my database. So instead of id you have I have products_id and I added other fields for the rating in the same table. I did this because I thought it is easier to fetch data of each product if I have in the same table.

    But I have an error that is troubling me. When I click the stars to vote my product. The error says ; Notice: Undefined index: products_id in C:xampphtdocsPhpProjectrate.php on line 9. Warning: mysql_num_rows(). How to solve it. Plz help.

    • Looks you have missed to import the table “ratings”.If not then try to echo the mysql query and error on mentioned line.
      echo $q=”select id from ratings”;
      if(!$r) eho mysql_error();

      Try these steps you will able to find the error.

      • Bibash Shah

        I was doing the way that I put all the fields of ur rating table’s in the same table product of mine. But now I am changing my mind to create another table rating with all the same fields and add one extra field products_id from my products table to keep on track the rating value of each products that I have in my database through products_id field. Do u think this will be the best way huh???

        Secondly. I tried the same way. But have error like (Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:xampphtdocsPhpProjectrate.php on line 12)

        I am sending you my Wholw code that you can understand my problems better way.
        [Starts frm here—–

        die(“Sorry, vote appears to be invalid.”); // kill the script because normal users will never see this.

        //if ($vote_sent > $units) die(“Sorry, vote appears to be invalid.”);

        //connecting to the database to get some information
        $query = mysql_query(“SELECT products_id,total_votes, total_value, used_ips FROM ratings WHERE id=’$id_sent’ “) or die(” Error: ” . mysql_error());
        $numbers = mysql_fetch_assoc($query);
        $checkIP = unserialize($numbers[‘used_ips’]);
        $count = $numbers[‘total_votes’]; //how many votes total
        $current_rating = $numbers[‘total_value’]; //total number of rating added together and stored
        $sum = $vote_sent + $current_rating; // add together the current vote value and the total vote value
        $tense = ($count == 1) ? “vote” : “votes”; //plural form votes/vote
        // checking to see if the first vote has been tallied
        // or increment the current number of votes
        ($sum == 0 ? $added = 0 : $added = $count + 1);

        // if it is an array i.e. already has entries the push in another value
        ((is_array($checkIP)) ? array_push($checkIP, $ip) : $checkIP = array($ip));
        $insertip = serialize($checkIP);

        //IP check when voting
        if (!isset($_COOKIE[‘rating_’ . $id_sent])) {
        $voted = mysql_num_rows(mysql_query(“SELECT used_ips FROM ratings WHERE used_ips LIKE ‘%” . $ip . “%’ AND id='” . $id_sent . “‘ “));
        $voted = 1;
        if (!$voted) { //if the user hasn’t yet voted, then vote normally…
        if (($vote_sent >= 1 && $vote_sent <= $units)) { // keep votes within range, make sure IP matches
        $update = "UPDATE ratings SET total_votes='" . $added . "', total_value='" . $sum . "', used_ips='" . $insertip . "' WHERE id='$id_sent'";
        $result = mysql_query($update);
        if ($result)
        setcookie("rating_" . $id_sent, 1, time() + 2592000);
        } //end for the "if(!$voted)"
        // these are new queries to get the new values!
        $newtotals = mysql_query("SELECT total_votes, total_value, used_ips FROM ratings WHERE id='$id_sent' ") or die(" Error: " . mysql_error());
        $numbers = mysql_fetch_assoc($newtotals);
        $count = $numbers['total_votes']; //how many votes total
        $current_rating = $numbers['total_value']; //total number of rating added together and stored
        $tense = ($count == 1) ? "vote" : "votes"; //plural form votes/vote
        // $new_back is what gets 'drawn' on your page after a successful 'AJAX/Javascript' vote
        if ($voted) {
        $sum = $current_rating;
        $added = $count;
        $new_back = array();
        for ($i = 0; $i < 5; $i++) {
        $j = $i + 1;
        if ($i < @number_format($current_rating / $count, 1) – 0.5)
        $class = "ratings_stars ratings_vote";
        $class = "ratings_stars";
        $new_back[] .= '’;

        $new_back[] .= ‘ Rating: ‘ . @number_format($sum / $added, 1) . ‘/’ . $units . ‘ (‘ . $count . ‘ ‘ . $tense . ‘ cast) ‘;
        if (!$voted)
        $new_back[] .= ‘Thanks for voting!‘;
        else {
        $new_back[] .= ‘Already voted for this item‘;
        $allnewback = join(“n”, $new_back);

        // ========================

        $output = $allnewback;
        echo $output;

        ends here]

        I amexpecting help from you sir. Thanks in advance…

        • echo all queries before line.12 and run the same queries from PHPMyAdmin you will easily able to find out error.

  • Stephen

    if the items have already been rated, and i load the the page at a later date, how can i show the ratings without clicking..

    Nice Work
    Thank you

    • it’s already show the rating without clicking.

      • StepHen

        Thank you for replying…. It appears I have to select one of the stars to show the average rating and to show that i have already submitted a rating for the item from that IP. I would like to see this stuff load when i enter the page, since i have already submitted a rating for that item.

        thanks again

        • It’s not a good technique to show rated star on based of IP because lots of people uses dynamic IP.Instead of IP you can use cookie to do same thing.To do this you can use Java Script code which will run after each page load and mark the item as rated if cookie for that item is present visitors browser.

          • Stephen

            I will try that with an onload event in javascript.

  • murali

    Mr.Amit, why am I getting ‘Sorry, vote appears to be invalid’ error

    • Make sure vote value is not greater that 5 or increase the value of $units in settings.php

  • Bibash Shah

    Could you help me in google hangout sir?

    • Please share your problem via comments.

      • Bibash Shah

        I do not understand some codes of line here.. like;

        $id_sent = preg_replace(“/[^0-9]/”,””,$_REQUEST[‘id’]);

        ok here the is created ..

        $q=mysql_num_rows(mysql_query(“select id from ratings where id=$id_sent”));
        And here the id is used.. But how can I use the id from database that I have used it as a product_id.

        • First line eliminates non-numeric characters from users input, it is just for security.Every time rating widgets appear on page it contains the id of product you just need to insert the ratings in table with that id.

          • Bibash Shah

            if (!$q)mysql_query(“insert into products (date) values (curdate())”);

            In the above query; I do not need id field as you have in your code because I already have the product with it’s id. But this query is making a new row and inserting a current date in the newly made row. Why is this. I hope the query is trying to insert the current date, when the item is rated. How can I fix this. And one other thing is that Ip address is not inserting in the table. Please help. Thanks in advance.

    • Ok add me on hangout.

  • fatima

    help me plzzzz

  • fatima

    please meri help kr doo 🙁

  • John

    Hello, can any one tell me how to show the result when i load the page plz ? it happens that when I open the page again, I get empty stars. thanks a lot

  • jay pangam

    i have to add ratings container individually …can you please mail me code to

  • lloyd

    Great Tutorial bro. really appreciate it

  • abc

    Sorry, vote appears to be invalid.

  • abc

    Sorry, vote appears to be invalid.error solutions when we click on it

  • Andrea Nutri

    is it possible to add 1 decimal to the voting (for example 4,2/5)

  • Yusuf Teke

    thenk bro

  • Pritam Saha

    i just say cool , no need to change anything accept database name[xxx] …. thanks bro..

  • mod

    Thank you for the script, just what I’ve been looking for. But I got this error when I imported the file ratings.sql to phpmyadmin. Could you tell me what I did wrong? I’m sure that I entered correct host,unname, pass and rating_dbname.

    SQL query:

    — Database: mr

    — ——————————————————–

    — Table structure for table ratings

    id int(10) NOT NULL,
    total_votes int(5) NOT NULL DEFAULT ‘0’,
    total_value int(5) NOT NULL DEFAULT ‘0’,
    used_ips longtext NOT NULL,
    PRIMARY KEY (id)

    MySQL said:

    #1046 – No database selected

    I ignored the error then opened rating.php. These are the error messages I got from rating.php. BTW I see the star ratings.

    No database selected
    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home1/xxx/public_html/rating2/rating.php on line 21

    If I rate it, it also shows another error message.

    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /home1/jsm6wat8/public_html/rating2/rate.php on line 9
    Error: SELECT command denied to user ‘xxx’ for table ‘ratings’

    I googled and found that some say I have to grant all privileges but did not work. I tried select only but nothing. Pls help.

  • mod

    Thank you for the script. It worked just fine but once I reboot the computer, it doesn’t work anymore. It shows an error. I googled it and tried some solutions but they don’t seem to work at all.
    This is all the page shows. Pls help.

    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /home1/xxx/public_html/rating2/rate.php on line 9

    Rating: 0.0/5 ( votes cast) Thanks for voting!