0

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

2
Contributors
4
Replies
19
Views
1 Year
Discussion Span
Last Post by diafol
0

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.

0

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?

2

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.

Votes + Comments
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
1

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.