Currently I have the code below for a star rating system that sends the information to the database and then shows an average in the front end via JS/Ajax. It currently records the users IP address and then a piece of javascript stops the user from voting again. I'm trying to adjust it so that instead of recording the IP address, it records the user ID of whoever is logged in at the time, with no luck so far. I also need to record which article the user has voted on, which is displayed at the end of the URL.
The HTML:
<fieldset id=demo1 class="rating">
<input class="stars" type="radio" id="star5" name="rating" value="5" />
<label class = "full" for="star5" title="5 stars"></label>
<input class="stars" type="radio" id="star4" name="rating" value="4" />
<label class = "full" for="star4" title="4 stars"></label>
<input class="stars" type="radio" id="star3" name="rating" value="3" />
<label class = "full" for="star3" title="3 stars"></label>
<input class="stars" type="radio" id="star2" name="rating" value="2" />
<label class = "full" for="star2" title="2 stars"></label>
<input class="stars" type="radio" id="star1" name="rating" value="1" />
<label class = "full" for="star1" title="1 star"></label>
</fieldset>
The JS:
$(document).ready(function () {
$("#demo1 .stars").click(function () {
$.post('http://kb.lorol.ispwebhost.com/includes/rating.php',{
rate:$(this).val()
},function(d){
if(d>0){
alert('You already rated');
}else{
alert('Thanks For Rating');
}
});
$(this).attr("checked");
});
});
The PHP:
$user_id = (isset ($_SESSION['user_id'])) ? $_SESSION['user_id'] : 0;
$servername = "localhost"; // Server details
$username = "root";
$password = "root";
$dbname = "test_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Unable to connect Server: " . $conn->connect_error);
}
if (isset($_POST['rate']) && !empty($_POST['rate'])) {
$rate = $conn->real_escape_string($_POST['rate']);
// check if user has already rated
$sql = "SELECT `id` FROM `tbl_rating` WHERE `user_id`='" . $user_id . "'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
if ($result->num_rows > 0) {
echo $row['id'];
} else {
$sql = "INSERT INTO `tbl_rating` ( `rate`, `user_id`) VALUES ('" . $rate . "', '" . $user_id . "'); ";
if (mysqli_query($conn, $sql)) {
echo "0";
}
}
}
$conn->close();