How To Code Rating/Liking System Using PHP/MySQL
I have come to know that most growing PHP Developers have difficult to write a liking or rating system, yes both of them goes alike with the same codeline. The below code is for rating system, just change some wordings and it becomes of liking system.
Now in this code, you are to create only one table for it, name it rate_item_table containing with the following columns below:
- id
- user_id
- item_id
- date
Note: You are to edit it and add your own user_id because i used user_id as ‘1’ throughout the code (User_id can be stored in sessions)
Where I wrote item_table is the table for the items, you will change it to yours
When you are done creating the columns and table, now run the codes below
<?php
//db connections
//if the $_GET[] function is not loaded
if(empty($_GET['rate']))
{
?>hello<br/>
<a href='?rate=1'>
<?php
echo mysql_num_rows(mysql_query("select * from rate_item_table where id='1'"));?> RATE</a><?php
}
if(isset($_GET['rate']))
{
//assigning the value of $_GET[] function to variable
$rate = mysql_real_escape_string(trim($_GET['rate']));
//checking if the value of $_GET['rate'] is in the database
if(mysql_num_rows(mysql_query("select * from item_table where id='$rate'"))<=0)
{
echo"The item you are to rate does not exist";
}
//Now we are going to check if the user already rated the item, am using user_id as 1, you can hold yours with a session or anything you want to
elseif(mysql_num_rows(mysql_query("select * from rate_item_table where user_id='1' and item_id='$rate'"))>0)
{
echo"You have already rated this item";
}
//now since the user has not rated the item before, let him rate it now
else
{
//Now inserting into to database
mysql_query("insert into rate_item_table(user_id,item_id,date)values('1','$rate','".time()."')")or die(mysql_error());
//redirecting back to the url that referred it here
header('location: '.$_SERVER['PHP_SELF'].'');
}
}
?>
Now run and see!
Works in Mozilla, Opera and Chrome only!