我想要实施一些不允许用户进行多次评分的操作 [英] I want to implement something that doesn't allow the user to rate more than once

查看:77
本文介绍了我想要实施一些不允许用户进行多次评分的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了使用ipaddress方式的其他人的代码.但是,我想使用一个代码来检查当前的用户ID和ID号.

I have used someone else's code that uses the ipaddress way. However, I would like to use a code that checks for the current userid and the id number.

$ipaddress = md5($_SERVER['REMOTE_ADDR']); // here I am taking IP as UniqueID but you can have user_id from Database or SESSION

/* Database connection settings */
$con = mysqli_connect('localhost','root','','database');

if (mysqli_connect_errno()) {
    echo "<p>Connection failed:".mysqli_connect_error()."</p>\n";
}   /* end of the connection */

if (isset($_POST['rate']) && !empty($_POST['rate'])) {
    $rate =  mysqli_real_escape_string($con, $_POST['rate']);
    // check if user has already rated
    $sql = "SELECT `id` FROM `tbl_rating` WHERE `user_id`='" . $ipaddress . "'";
    $result = mysqli_query( $con, $sql);
    $row =  mysqli_fetch_assoc();//$result->fetch_assoc();
    if (mysqli_num_rows($result) > 0) {
        //$result->num_rows > 0) {
        echo $row['id'];
    } else {
        $sql = "INSERT INTO `tbl_rating` ( `rate`, `user_id`) VALUES ('" . $rate . "', '" . $ipaddress . "'); ";
        if (mysqli_query($con, $sql)) {
            echo "0";
        }
    }
}
//$conn->close();

推荐答案

在数据库表中,将user_id列设置为UNIQUE KEY.这样,如果用户尝试进行第二次投票,则数据库将拒绝INSERT查询,并且您只可以在受影响的行= 0时显示一条消息.

In your database table, set the user_id column as UNIQUE KEY. That way, if a user tries to cast a second vote, then the database will deny the INSERT query and you can just display a message when affected rows = 0.

或者,(从UX角度来看更好),您可以在加载页面内容之前先对登录的用户执行SELECT查询:

Alternatively, (and better from a UX perspective) you can preemptively do a SELECT query for the logged in user before loading the page content:

$allow_rating = "false";  // default value

if (!$conn = new mysqli("localhost", "root","","database")) {
    echo "Database Connection Error: " , $conn->connect_error;  // never show to public
} elseif (!$stmt = $conn->prepare("SELECT rate FROM tbl_rating WHERE user_id=? LIMIT 1")) {
    echo "Prepare Syntax Error: " , $conn->error;  // never show to public
} else { 
    if (!$stmt->bind_param("s", $ipaddress) || !$stmt->execute() || !$stmt->store_result()) {
        echo "Statement Error: " , $stmt->error;  // never show to public
    } elseif (!$stmt->num_rows) {
        $allow_rating = "true";  // only when everything works and user hasn't voted yet
    }
    $stmt->close();
}

echo "Rating Permission: $allow_rating";

如果他们在表中已经有一行,那么甚至不要给他们再次提交的机会.

And if they already have a row in the table, then don't even give them the chance to submit again.

这篇关于我想要实施一些不允许用户进行多次评分的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆