我想实现一些不允许用户评价多次的内容

时间:2017-04-04 23:02:18

标签: php mysqli sql-insert unique-key

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

$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();

1 个答案:

答案 0 :(得分:6)

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

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

$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";

如果他们已经在桌子上排了一排,那么就不要给他们再次提交的机会。