Reputation: 65
I am trying to create a rating system with my gallery. I can get all the images to appear on the page with a button which says "like this image". The aim is that a user can only like an image once and that once they click the "like" button, the value 1 will be added to the image in the database. I have a a database table called images with ImageID, image and rating.The initial value of rating is zero when someone uploads an image. Here is the code i used to grab the images from the database table to appear with a button:
<?php
mysql_connect("localhost","root","");
mysql_select_db("pardeepsandhu");
$res= mysql_query("select * from images");
$row=mysql_fetch_array($res);
?>
<?php
?>
<div id="w">
<div id="content">
<div id="images"><?php while ($row=mysql_fetch_array($res)){?>
<div id="pic" style="display:inline-block">
<a href="<?php echo $row["Image"]; ?>"><img src="<?php echo $row["Image"]; ?>" height="135" width="135" border="5" alt="turntable" /></a>
<form id="form1" name="form1" method="post" action="">
<input type="submit" name="rate" id="rate" value="Like this image"/>
</form>
</div>
<?php } ?>
</div>
</div>
</div>
<script type="text/javascript">
$(function() {
$('#images a').lightBox();
});
</script>
I know that i will need a if(isset($_POST['rate'])){} initially to get the ball rolling, however i don't know how to make it. If a user clicks a button under an image, the rate column in the database will increase by one and the user can only do this once on an image. Can someone help? Thanks!
Upvotes: 0
Views: 716
Reputation: 799
I recommend a slightly different approach. In order to track who's rated what images, make a new DB table with columns userID
and imageID
. To get an image's score, you can just count the number of rows where imageID
is the current image's ID, and to check if a user has already rated the image, check if a row exists such that imageID
= current image and userID
= current user.
// $curID is the current image ID
$query = "SELECT * FROM `ratings` WHERE `imageID` = $curID";
// use mysqli->num_rows
// $curUser, $curID are current user ID, current image ID
$query = "SELECT * FROM `ratings` WHERE `imageID` = $curID AND `userID` = $curUser;";
// check if mysqli->num_rows > 0
$query = "INSERT INTO `ratings` (`userID`, `imageID`) VALUES ($curID, $curUser);";
Upvotes: 3