James John – Software Engineer

How To Code Rating/Liking System Using PHP/MySQL

Hi all,

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

  1. <?php
  2. //db connections
  3. //if the $_GET[] function is not loaded
  4. if(empty($_GET['rate']))
  5. {
  6. ?>hello<br/>
  7. <a href='?rate=1'>
  8. <?php
  9. echo mysql_num_rows(mysql_query("select * from rate_item_table where id='1'"));?> RATE</a><?php
  10. }
  11. if(isset($_GET['rate']))
  12. {
  13. //assigning the value of $_GET[] function to variable
  14. $rate = mysql_real_escape_string(trim($_GET['rate']));
  15. //checking if the value of $_GET['rate'] is in the database
  16. if(mysql_num_rows(mysql_query("select * from item_table where id='$rate'"))<=0)
  17. {
  18. echo"The item you are to rate does not exist";
  19. }
  20. //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
  21. elseif(mysql_num_rows(mysql_query("select * from rate_item_table where user_id='1' and item_id='$rate'"))>0)
  22. {
  23. echo"You have already rated this item";
  24. }
  25. //now since the user has not rated the item before, let him rate it now
  26. else
  27. {
  28. //Now inserting into to database
  29. mysql_query("insert into rate_item_table(user_id,item_id,date)values('1','$rate','".time()."')")or die(mysql_error());
  30. //redirecting back to the url that referred it here
  31. header('location: '.$_SERVER['PHP_SELF'].'');
  32. }
  33. }
  34. ?>

Now run and see!

Works in Mozilla, Opera and Chrome only!

James John

Software Engineer