Tutorials

Article Content:create rating system with raty plugin and codeigniter

create rating system with raty plugin and codeigniter

create rating system with raty plugin and codeigniter.

this week I thought to change rating system in my own CodeIgniter CMS ,so I started to search for many plugins,there are many plugins,some with jquery and other with pure javascript
after a search, I decided finally to use Raty plugin because it easy and clean code also ha many features to fit your needs,
after integrating it with CodeIgniter I thought to share one tutorial to make this easy as possible,I put in my mind different situations when you want to make rating related to (post id,user id) ,my code clean ,simple and commented. so let's go dude wink
go to this site and download this plugin,place it in your root path,in my situation it was a global directory

1- create database schema we have two tables one for rating another to users rating

--
-- Table structure for table `d_rating`
--

CREATE TABLE IF NOT EXISTS `d_rating` (
  `rt_id` int(11) NOT NULL,
  `rt_item_id` int(11) NOT NULL,
  `rt_total_rates` int(11) NOT NULL,
  `rt_total_points` decimal(10,1) NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=26 ;

--
-- Dumping data for table `d_rating`
--

INSERT INTO `d_rating` (`rt_id`, `rt_item_id`, `rt_total_rates`, `rt_total_points`) VALUES
  (25, 444444, 1, '2.5');


--
-- Table structure for table `d_rating`
--

CREATE TABLE IF NOT EXISTS `d_rating_users` (
  `rtu_id` int(11) NOT NULL,
  `rtu_rate_id` int(11) NOT NULL,
  `rtu_user_id` int(11) NOT NULL,
  `rtu_created` int(11) NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

 

2-  add new controller file with name rating.PHP

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class rating extends front_end
{
    // default user and post id ,you can change
    public $user_id = 10 ;
    public $post_id = 444444;

    function __construct()
    {
        parent::__construct();

        $this->lang->load('rating/rating');
        $this->load->model('rating_model','rating');
        $this->load->library('form_validation');
    }

    /**
     *  display all ratings in specfic article.
     */
    function index()
    {
        $data["post_id"] = $this->post_id;
        $data["is_rated"] =  $this->rating->get_user_numrate($this->post_id,$this->user_id);

        $total_rates = 0;
        $total_points = 0;
        $query1 = $this->rating->get_article_rate($this->post_id);
        // check if article has rate if yes get it
        if($query1 !== false){
            $total_rates = $query1->rt_total_rates;
            $total_points = $query1->rt_total_points;
        }
        // if rating greater than zero
        // dived total rats on total rates and send it to view
        // else send zero to view
        if($total_points > 0 and $total_rates > 0){
            $ratings = $total_points/$total_rates;
            $data["ratings"] = $total_points/$total_rates;
            $data["rates"] = $ratings;
        }else{
            $data["rates"] = 0;
        }
        $this->load->view('site/ratings',$data);
    }

    // create new rate
    function create_rate()
    {
        $this->user_id = 10;

            $post_id= $this->input->post("pid");
            $rate=  $this->input->post("score");

            //check the article is rated already

             $rated = $this->rating->get_rate_numbers($post_id);
            if($rated == 0 ) {
                // if no send new rate record
                $rate_query = $this->rating->insert_rate($post_id,$rate,$this->user_id);
            }else {
                // else get rate id and update value
                $rate_id = $this->rating->get_article_rate($post_id);
                $rate_query =  $this->rating->update_rate($rate_id->rt_id,$rate,$this->user_id);

            }
    /// after this see Succesfull msg
        if($rate_query)
        {
            echo "Voting Succesfull";
        }
    }
}

3- add new model file with rating.php

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class rating_model extends CI_Model {

    function __construct() {
        parent::__construct();
    }


    /*  This function get ratings count number
    related to specfic item id.
     */

    function get_rate_numbers($post_id) {
        $rate_num = $this->db->query("select * from d_rating where rt_item_id='$post_id'")->num_rows();
        return $rate_num;
    }

    /*
 * This function check if user
    has rate specfic item or not
*/
    function get_user_numrate($post_id,$userid) {
        $rate_num = $this->db->query("
        select * from d_rating
         INNER JOIN d_rating_users ON rtu_rate_id = rt_id
         where rt_item_id ='$post_id'
         AND  rtu_user_id ='$userid' ");
        if ($rate_num->num_rows() > 0) {
            return true;
        }else{
            return false;
        }
    }

    /*  This function get ratings
    related to specfic item id. */

    function get_article_rate($post_id) {
        $query = $this->db->query("select * from d_rating where rt_item_id='$post_id'");
        if ($query->num_rows() > 0)
        {
            $result = $query->row();
            return $result;

        }else{
            return false;
        }
    }
    /*  This function insert ratings
    with item id and user id. */

    function insert_rate($id,$rate,$user_id) {
        $this->db->query("insert into d_rating values('','$id','1','$rate')");
        $last_id = mysql_insert_id();
        $this->db->query("insert into d_rating_users values('',$last_id,$user_id,UNIX_TIMESTAMP())");
        return true;
    }

    function update_rate($id,$rate,$user_id) {

        $upadte_rate1=$this->db->query("select * from d_rating where rt_item_id='$id'")->row();
        $total_rates= $upadte_rate1->rt_total_rates+1;
        $total_points= $upadte_rate1->rt_total_points+$rate;
        $rate_id= $upadte_rate1->rt_id;
        $this->db->query("update d_rating set rt_total_rates='$total_rates', rt_total_points='$total_points' where rt_id='$rate_id'");
        $this->db->query("insert into d_rating_users values('','$id',$user_id,UNIX_TIMESTAMP())");

        return true;
    }
}

4- add view file to show rating with name ratings.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Jquery Raty usage in PHP - Simple Star Ratting Plugin</title>
</head>
<body>
<div>
    <!-- We use three products below and make DIVs with class star for showing stars -->
    <h3>Mobile</h3>
    <p>it a first product (444444)</p>
    <div id="444444" class="<?= $post_id ?>"></div>

    <h3>Laptop</h3>
    <p>it a second product (666666)</p>
    <div id="666666" class="star"></div>

    <h3>Magazine</h3>
    <p>it a third product (777777)</p>
    <div id="777777" class="star"></div>

</div>
<!-- Jquery and Raty Js with scrpt having class star
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->

<script src="<?= base_url() ?>global/site/rating/js/jquery.min.js"></script>
<!--For Raty-->
<script type="text/javascript" src="<?= base_url() ?>global/site/rating/js/jquery.raty.min.js"></script>

<script type="text/javascript">

    $(function() {
        <!-- Below line will get stars images from img folder -->
        $.fn.raty.defaults.path = '<?= base_url() ?>global/site/rating/img';
        <!-- Below block code will post score and pid to raty1.php page where you will insert/update it into database. you can also change raty settings also from here. please read documentations -->
        $(".<?= $post_id ?>").raty({
            <?php if(isset($rates) and $rates != 0){ ?>
            start:     <?= $rates ?>,
              <?php  } ?>
            <?php if($is_rated == true){ ?>
             readOnly:   true,
              <?php  } ?>
            half  : true,
            number: 5,
            score : 0,
            click: function(score, evt) {

                var pid=$(this).prop('id');
                $.post('<?= base_url()?>rating/create_rate',{score:score, pid:pid},
                    function(data){
                        alert(score);
                        return $.fn.raty.readOnly(true, '.<?= $post_id ?>');
                    });

            }

        });

    });
</script>
</body>
</html>

 



  • George
    Hi this is not working for me. Can you please take a look on it and update if it is possible? I am trying to bild a rating system on Codeigniter 3.0.1. Is this 3.0 version or 2.2? Thanks in advance ;)
    September 9, 2015
    Reply
    • admin
      webeaystep@gmail.com
      Hi George,you are welcome about your questions,yes it was for version 2.x.x but i think it will work also with version 3.x.x because no much changes between these two versions.
      September 10, 2015
      Reply
  • mex
    Sorry, could you give a complete project. Because, its not complete project
    February 5, 2016
    Reply
    • admin
      webeasystep@gmail.com
      sorry mex this all i have for this project,if you want a complete code you can use bootstrap star rating. you are welcome
      February 6, 2016
      Reply
  • nonah lynn cabilao
    Can you give me the complete project? coz its not working.
    February 9, 2016
    Reply
    • admin
      info@webeasystep.com
      sorry , nonah this is old project ,in the present i have my own webesasystep repository in bitbucket to store all new projects
      February 13, 2016
      Reply
  • eka
    the front_end class inside core folder can you included as well, thank you
    February 11, 2016
    Reply
    • admin
      info@webeasystep.com
      eka , you can change it to ci_controller and it should work correctly
      February 13, 2016
      Reply
  • Zodd
    Can I get the source files for this project or your newer one??
    March 2, 2016
    Reply
  • teetu
    Can you please tell me from where to download the javascript and css for stars.
    May 13, 2016
    Reply
    • admin
      info@webeasystep.com
      from here http://krainasmoka.pl/js/rating/
      May 13, 2016
      Reply
  • Salman
    How to use this system for multiple item in single page.
    December 15, 2017
    Reply
    • admin
      info@webeasystep.com
      i recommended to use bootstrap star rating as alternative
      December 18, 2017
      Reply

Leave a Reply

Your email address will not be published.


Notify me of followup comments via e-mail.
You can also Subscribe without commenting.