how to make a five star rating system in codeigniter

Codeigniter

Hi everyone here we are going to make a five star rating system using php codeigniter framework. Please go throw the steps to do create the star rating system in codeigniter.

Step 1: Crate database and tables and insert the data.

Create two tables posts and ratings and dumb the data to tables.

post table:-

CREATE TABLE `posts` (
 `post_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
 `post_content` text NOT NULL,
 `post_title` varchar(40) NOT NULL,
 `post_created_on` timestamp NOT NULL CURRENT_TIMESTAMP,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
--Dumping data for table`posts`
--

INSERT INTO `posts` (`post_id`, `post_content`, `post_title`, `post_created_on`,) VALUES
(1, `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum
 has been the industry's standard dummy text ever since the 1500s, when an unknown
 printer took a galley of type and scrambled it to make a type specimen book.`,
`what is lore ipsum?`,1555570050),
(2, `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum
 has been the industry's standard dummy text ever since the 1500s, when an unknown
 printer took a galley of type and scrambled it to make a type specimen book.`,
`where does it come from?`,15555700145),
(3, `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum
 has been the industry's standard dummy text ever since the 1500s, when an unknown
 printer took a galley of type and scrambled it to make a type specimen book.`,
`why do we use it?`,1555570049),
(4, `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum
 has been the industry's standard dummy text ever since the 1500s, when an unknown
 printer took a galley of type and scrambled it to make a type specimen book.`,
`where can i get some?`,1555570251),

--
-- Indexes for dumped tables
--
rating table:-

CREATE TABLE `rating` (
`rate_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`rate_post_id` int(2) NOT NULL,
`rating` int(2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
-
-- Dumping data for table `rating`
--

INSERT INTO `rating` (`rate_id`, `rate_post_id`, `rating`) VALUES
(1, 1, 1),
(2, 1, 5),
(3, 1, 3),
(4, 1, 4),
(5, 2, 3),
(6, 3, 5),
(7, 2, 3),
(8, 4, 2),
(9, 4, 4),;

--
-- Indexes for dumped tables
--
Step-2 : Create a new controller

Open application/controllers directory of your codeigniter web application. Create a new file and save it as Starrating.php, after that copy below code and paste it in your Starrating.php controller.

index() method  – Fetch all posts and and each post average rating. Then pass this data to view page.

rate() method  –  Insert new post rate to rating table.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php defined('BASEPATH') OR exit('No direct script access allowed'); 
      class Starrating extends CI_Controller { 
        function __construct() { 
            parent::__construct(); 
            $this->load->model('StarModel','star');
	}
	public function index()
	{
		$data['posts'] = $this->star->fetch_post();
		if(!empty($data['posts']))
		{
			foreach ($data['posts'] as $key => $value) {
				$star = $this->star->post_rating($value['post_id']);
				if(isset($star))
					$data['posts'][$key]['star'] = $star['rate_rates'];
			}
		}
		$this->load->view('starrating',$data);

	}
	public function rate()
	{
		if($this->star->rate_post($_POST['i'],$_POST['post']))
			echo true;
		else
			echo false;

	}
}
Step-3 : Create model

Create new model under application/models directory and name it as StarModel.php.  All database connections like insert,update,select etc are writing here. This model contains three functions. First one fetch_post() is used to fetch all posts from posts table. post_rating() fetch the average rate of requested post. Finally the last function rate_post() insert new rate entry of selected post.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 
class StarModel extends CI_Model { 
       public function fetch_post() { 
		$query = $this->db->get('posts');
		$result = $query->result_array();
		return $result;
	}
	public function post_rating($post = null)
	{
		if(isset($post) && $post != null)
		{	
			$this->db->select('AVG(rate_rates) as rate_rates');
			$where = ['rate_post_id' => $post];
			$this->db->where($where);
			$query = $this->db->get('rating');
			$result = $query->row_array();
			return $result;
		}
	}
	public function rate_post($rate,$post)
	{
		$data = ['rate_post_id' => $post, 'rate_rates' => $rate,'rate_rated_on' 
=> date('Y-m-d H:i:s')];
		$this->db->insert('rating',$data);
		return true;
	}
}
Step-4: Load database library

Open autoload.php file under application/config/  directory and add database library.

$autoload['libraries'] = array('database');

 

Step-5: View page

Create a starrating.php file in your application/views/ directory of your codeigniter application.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<html>
 <head>
 <title>Star Rating</title>
 <!-- Latest compiled and minified CSS -->  
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstr
ap.min.css">
 <!-- jQuery library -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</script>
 <!-- Latest compiled JavaScript -->
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js">
</script>
  <style type="text/css">
     .star:hover{.star:hover{ cursor: pointer; } 
   </style>
 </head>
 <body>
    <div class="container"> 
      <div><h4>Jquery Ajax Star raing using Codeigniter</h4></div>
         <?php 
         if(isset($posts)) { 
             foreach ($posts as $key => $value) { 
                if(isset($value['post_id'])){ ?>
                   <div class="row">
                       <div class="col-md-12"> 
                           <h4><?= $value['post_title'] ?></h4> 
                           <p><?= $value['post_content'] ?></p> 
                          <p> rating :
                          <?php
                          $i = 1; 
                          while ($i<6) {
                           
                            if(isset($value['star']) && $value['star']!= ''){
				if($value['star'] < $i) { 
                                   //gray star ?> <span class="fa fa-star star" style="
color:#ccc;" data-id="<?= $i ?>" data-post="<?= $value['post_id'] ?>"></span>  <?php
				}else{
                                   //golden star//golden star ?> <span class="fa fa-star 
star" style="color:#ffcc00;" data-id="<?= $i ?>" data-post="<?= $value['post_id'] ?>">
</span> <?php 
                                }
			    }else{ 
                                   //gray star ?> <span class="fa fa-star star" style="
color:#ccc;" data-id="<?= $i ?>" data-post="<?= $value['post_id'] ?>"></span> <?php 
                            }
                            $i++; 
                         } ?>
                     </p>
                   </div>
              </div>
             <?php }
             }
          } ?> 
    </div>
    <script type="text/javascript">
         $('.star').on({ 
            click: function(){
		var i = $(this).data('id');
		var post = $(this).data('post');
                if(i != '' && post != '')
		{
			$.ajax({
			        url : "",
				method :'post',
				data:{i:i,post:post},
				success: function(data)
				{
				      location.reload();
				}
			});
		}
	    }
	});
    </script> 
 </body> 
</html>
Step-6: Run

Finally run your application….!

Leave a Reply

Your email address will not be published. Required fields are marked *