I want to implement something that doesn't allow the user to rate more than once

天大地大妈咪最大 提交于 2020-01-07 09:28:17

问题


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

回答1:


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.

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.



来源:https://stackoverflow.com/questions/43219134/i-want-to-implement-something-that-doesnt-allow-the-user-to-rate-more-than-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!