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

时间:2015-07-15 10:58:36

标签: php jquery mysql

目前我有一个星级评分系统的代码,它将信息发送到数据库,然后通过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();

0 个答案:

没有答案