Rating system is very useful for every web project. Through this system, web admin can track the visitors like and dislike. Also it will help webmaster to understand the visitors choices and make their website more interactive with the visitors.
We have made the simple rating system using PHP, MySQL, jQuery and Ajax. This rating system take the visitors like or dislike with jQuery and Ajax. Also store the data at the database using PHP and MySQL. Once the total number of likes and dislikes is calculated, it will be displayed to the visitors. We have made the whole process very easy and you can implement the rating system at your project very easily.
This tutorial will discuss about like dislike system in PHP. We have used OOP concept in PHP for make the whole script lightweight, simple and easy.
Let’s start our tutorial. In this tutorial we will listing some tutorials with like and dislike icon. When like and dislike icon is clicked, like and dislike counter of that particular tutorial will be displayed beside those icons.
For testing purpose insert some data at the
We have made the simple rating system using PHP, MySQL, jQuery and Ajax. This rating system take the visitors like or dislike with jQuery and Ajax. Also store the data at the database using PHP and MySQL. Once the total number of likes and dislikes is calculated, it will be displayed to the visitors. We have made the whole process very easy and you can implement the rating system at your project very easily.
This tutorial will discuss about like dislike system in PHP. We have used OOP concept in PHP for make the whole script lightweight, simple and easy.
Let’s start our tutorial. In this tutorial we will listing some tutorials with like and dislike icon. When like and dislike icon is clicked, like and dislike counter of that particular tutorial will be displayed beside those icons.
Database Design:
Create a database likecodexworld
and create a table into this database named tutorials
. tutorials
table creation SQL will be like below.
CREATE TABLE `tutorials` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`details` text COLLATE utf8_unicode_ci NOT NULL,
`image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`like_num` bigint(10) NOT NULL,
`dislike_num` bigint(10) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active, 0=Inactive',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
For testing purpose insert some data at the
tutorials
table. The respective images will be stored into the images/
directory at the root folder.tutorial.php:
We have used PHP OOP concept for fetch, insert and update data from the database. So, at first we will create a file namedtutorial.php
and define Tutorial
class in this file.__constructor()
method will connect with MySQL database and select tutorials
table.get_rows()
function fetch the tutorial rows from the tutorials
table. By default get_rows()
function return all rows, but if a particular tutorial ID is provided, then it will be returned only that particular row.update()
function is used for update the tutorials data.
<?php
class Tutorial{
function __construct(){
//database configuration
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'codexworld';
//connect to the database
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($conn->connect_errno){
echo "Failed to connect to database: (" . $conn->connect_errno . ") " . $conn->connect_error;
}else{
$this->db = $conn;
}
}
function get_rows($id = ''){
if($id != ''){
//fetch single row
$query = $this->db->query("SELECT * FROM tutorials WHERE id = $id");
$data = $query->fetch_assoc();
}else{
//fetch all rows
$query = $this->db->query("SELECT * FROM tutorials");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$data[] = $row;
}
}else{
$data = array();
}
}
return $data;
}
function update($data = array(), $conditions = array()){
$data_array_num = count($data);
$cols_vals = "";
$condition_str = "";
$i=0;
foreach($data as $key=>$val){
$i++;
$sep = ($i == $data_array_num)?'':', ';
$cols_vals .= $key."='".$val."'".$sep;
}
foreach($conditions as $key=>$val){
$i++;
$sep = ($i == $data_array_num)?"":" AND ";
$condition_str .= $key."='".$val."'";
}
//update data
$update = $this->db->query("UPDATE tutorials SET $cols_vals WHERE $condition_str");
return $update?TRUE:FALSE;
}
}
?>
index.php:
At the beginning of the file, we will includetutorial.php
file and create an instance of Tutorial class. Call the get_rows()
function and stored all tutorials data into $trows
variable.cwRating()
is a JavaScript function and we will used this function into onClick
event of like or dislike icon. Also passing the tutorial ID in first parameter, rating type(1=Like, 0=Dislike) in the second parameter and counter element ID in the third parameter.
<?php
include_once("tutorial.php");
$tutorial = new Tutorial();
//get tutorials data from database
$trows = $tutorial->get_rows();
?>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
/**
* Function Name: cwRating()
* Function Author: CodexWorld
* Description: cwRating() function is used for implement the rating system. cwRating() function insert like or dislike data into the database and display the rating count at the target div.
* id = Unique ID, like or dislike is based on this ID.
* type = Use 1 for like and 0 for dislike.
* target = Target div ID where the total number of likes or dislikes will display.
**/
function cwRating(id,type,target){
$.ajax({
type:'POST',
url:'rating.php',
data:'id='+id+'&type='+type,
success:function(msg){
if(msg == 'err'){
alert('Some problem occured, please try again.');
}else{
$('#'+target).html(msg);
}
}
});
}
</script>
<!-- Tutorials listing -->
<?php foreach($trows as $trow){ ?>
<div class="thumbnail">
<img src="<?php echo 'images/'.$trow['image']; ?>" alt="" />
<div class="caption">
<h4><a href="javascript:void(0);"><?php echo $trow['title']; ?></a></h4>
<p><?php echo $trow['details']; ?></p>
</div>
<div class="ratings">
<p class="pull-right"></p>
<p>
<!-- Like Icon HTML -->
<span class="glyphicon glyphicon-thumbs-up" onClick="cwRating(<?php echo $trow['id']; ?>,1,'like_count<?php echo $trow['id']; ?>')"></span>
<!-- Like Counter -->
<span class="counter" id="like_count<?php echo $trow['id']; ?>"><?php echo $trow['like_num']; ?></span>
<!-- Dislike Icon HTML -->
<span class="glyphicon glyphicon-thumbs-down" onClick="cwRating(<?php echo $trow['id']; ?>,0,'dislike_count<?php echo $trow['id']; ?>')"></span>
<!-- Dislike Counter -->
<span class="counter" id="dislike_count<?php echo $trow['id']; ?>"><?php echo $trow['dislike_num']; ?></span>
</p>
</div>
</div>
<?php } ?>
rating.php:
Once the like or dislike icon is clicked,rating.php
file is called. In this file we will fetch the previous numbers of likes or dislikes and increment the likes or dislikes numbers and returns the present numbers of likes or dislikes.
<?php
include_once("tutorial.php");
$tutorial = new Tutorial();
if($_POST['id']){
//previous tutorial data
$prev_record = $tutorial->get_rows($_POST['id']);
//previous total likes
$prev_like = $prev_record['like_num'];
//previous total dislikes
$prev_dislike = $prev_record['dislike_num'];
//calculates the numbers of like or dislike
if($_POST['type'] == 1){
$like = ($prev_like + 1);
$dislike = $prev_dislike;
$return_count = $like;
}else{
$like = $prev_like;
$dislike = ($prev_dislike + 1);
$return_count = $dislike;
}
//store update data
$data = array('like_num'=>$like,'dislike_num'=>$dislike,'modified'=>date("Y-m-d H:i:s"));
//update condition
$condition = array('id'=>$_POST['id']);
//update tutorial like dislike
$update = $tutorial->update($data,$condition);
//return like or dislike number if update is successful, otherwise return error
echo $update?$return_count:'err';
}
?>
Conclusion
In this tutorial, we’ve provided the script for implement rating system using PHP, MySQL, jQuery and Ajax in your project. As per this script a user can rate multiple times for the same item. If you want to restrict users from multiple times rating, you can do it by two ways.- Allow the user to vote after login. Here you can easily track User Id and allow the user to vote only once.
- Track the user IP address using
$_SERVER['REMOTE_ADDR']
and allow the user to vote only once.
Comments