I created a rating system where users can rate the posts, but I want to make it restrict like one user can only rate the post once I beleive my punctuation is better to be understandable like before as I got many negative feedbacks here but I am trying to improve my grammer :)

Okay so 1 user can only rate 1 post once not allowed to rate again and again how it can be done here is my code

star rating header code

$(function() {
                  $("#rating_star").codexworld_rating_widget({
                      starLength: '5',
                      initialValue: '',
                      callbackFunctionName: 'processRating',
                      imageDirectory: 'images/',
                      inputAttr: 'postID'
                  });
              });

              function processRating(val, attrVal){
                  $.ajax({
                      type: 'POST',
                      url: 'rating.php',
                      data: 'postID='+attrVal+'&ratingPoints='+val,
                      dataType: 'json',
                      success : function(data) {
                          if (data.status == 'ok') {
                              $('#avgrat').text(data.average_rating);
                              $('#totalrat').text(data.rating_number);
                          }else{
                              alert('Some problem occured, please try again.');
                          }
                      }
                  });
              }

rating code in body tag

<?php if(isset($_SESSION["uid"])) { ?>
    <input name="ratingPoints" value="0" id="rating_star" type="hidden" postID="<?php echo $pid; ?>" />
    <div class="overall-rating">(Average Rating <span id="avgrat"><?php echo $ratingRow['average_rating']; ?></span>
    Based on <span id="totalrat"><?php echo $ratingRow['rating_number']; ?></span>  rating)</span></div>
<?php } else { ?>

    <input id="input-21b" disabled value="<?php echo $ratingRow['average_rating']; ?>" type="number" name="starsvalue" class="rating" min=0 max=5 step=0.2 data-size="lg">
<?php } ?>
<script>
    jQuery(document).ready(function () {
        $("#input-21f").rating({
        starCaptions: function(val) {
        if (val < 3) {
            return val;
        } else {
            return 'high';
        }
    },
    starCaptionClasses: function(val) {
        if (val < 3) {
            return 'label label-danger';
        } else {
            return 'label label-success';
        }
    },
        hoverOnClear: false
    });

    $('#rating-input').rating({
        min: 0,
        max: 5,
        step: 1,
        size: 'lg',
        showClear: false
    });

});
</script>

rating

<?php
include_once ('includes/connection.php');
if(!empty($_POST['ratingPoints'])){
    $postID = $_POST['postID'];
    $ratingNum = 1;
    $ratingPoints = $_POST['ratingPoints'];

    //Check the rating row with same post ID
    $prevRatingQuery = "SELECT * FROM post_rating WHERE post_id = ".$postID;
    $prevRatingResult = mysqli_query($connection, $prevRatingQuery);
    if(mysqli_num_rows($prevRatingResult) > 0):
        $prevRatingRow = mysqli_fetch_assoc($prevRatingResult);
        $ratingNum = $prevRatingRow['rating_number'] + $ratingNum;
        $ratingPoints = $prevRatingRow['total_points'] + $ratingPoints;
        //Update rating data into the database
        $query = "UPDATE post_rating SET rating_number = '".$ratingNum."', total_points = '".$ratingPoints."', modified = '".date("Y-m-d H:i:s")."' WHERE post_id = ".$postID;
        $update = mysqli_query($connection, $query);
    else:
        //Insert rating data into the database
        $query = "INSERT INTO post_rating (post_id,rating_number,total_points,created,modified) VALUES(".$postID.",'".$ratingNum."','".$ratingPoints."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
        $insert = mysqli_query($connection, $query);
    endif;

    //Fetch rating deatails from database
    $query2 = "SELECT rating_number, FORMAT((total_points / rating_number),1) as average_rating FROM post_rating WHERE post_id = ".$postID." AND status = 1";
    $result = mysqli_query($connection, $query2);
    $ratingRow = mysqli_fetch_assoc($result);

    if($ratingRow){
        $ratingRow['status'] = 'ok';
    }else{
        $ratingRow['status'] = 'err';
    }

    //Return json formatted rating data
    echo json_encode($ratingRow);
}
?>

.php

Member Avatar for diafol

Your ratings table can be a primary key of post_id and user_id and then just a regular field for the rating. This will prevent the user from rating more than once.

so you are trying to say i will make post_id and user_id this will prevent user to rate twice on 1 post is that correct?

Member Avatar for diafol

Yes:

ratings table:

CREATE TABLE `ratings` (
  `post_id` int(10) unsigned NOT NULL,
  `user_id` int(10) unsigned NOT NULL,
  `rating` tinyint(2) DEFAULT NULL,
  PRIMARY KEY (`post_id`,`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

That sort of thing - obviously change the integer limit to something more sensible - not 10! If you rate out of 10, keep tinyint as 2, otherwise if to say 5, change tinyint to 1.

commented: reading about utf8mb4 made me think about it. I am not sure if it is worth refactoring but +1 for bringing that issue to notice +9
Member Avatar for diafol

Not sure if it would be worth refactoring. As you're aware utf-8 has pretty much got it covered for the BMP set. There are however, certain Chinese chars (and others) that require 4 bytes, or so I've heard - there seems to be a bit of confusion over this issue - some say utf8 has the complete Chinese set, others insist otherwise. I'm not fussy about my historical work, but am using mb4 as my default for current design. It may be a case of "the Emperor's got new clothes" - whether or not I will ever use supplementary chars is another thing. Emoticons ('yuck') though, may be mb4.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.