在数据库中记录用户ID而不是IP地址


Recording USER ID in database instead of IP address

目前我有下面的代码星级评级系统,发送信息到数据库,然后通过JS/Ajax在前端显示一个平均值。它当前记录用户的IP地址,然后一段javascript阻止用户再次投票。我正试图调整它,而不是记录IP地址,它记录的用户ID,无论谁登录的时间,没有运气到目前为止。我还需要记录用户投票的文章,这显示在URL的末尾。

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>

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");
     });
});
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();

您需要在AJAX请求中包含文章ID。你可以直接把它放到请求中,或者把它放到fieldset中,然后通过JavaScript/jQuery访问属性。

例如:

var article_id = '<?php echo $_GET['article'] ?>';
$.post(
    'http://kb.lorol.ispwebhost.com/includes/rating.php',
    {
        article_id: article_id,
        rate:       $(this).val()
    },
    function (d) {
        // ...
    }
);

在PHP中:

$article_id = isset($_POST['article_id']) && is_numeric($_POST['article_id'])
              ? $_POST['article_id']
              : 0;

另外,我建议使用JSON。还看到:

    jQuery: $.ajax()/$ . get ()/$ . post () PHP: json_decode()/json_encode()