作者:TheKing小狼 | 来源:互联网 | 2023-02-07 15:46
我使用过其他人使用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 "Connection failed:".mysqli_connect_error()."
\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();
mickmackusa..
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";
如果他们已经在表中排了一行,那么甚至不给他们再次提交的机会.
1> mickmackusa..:
在数据库表中,将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";
如果他们已经在表中排了一行,那么甚至不给他们再次提交的机会.
是啊.那应该是正常的.但我建议添加一个新表,包含user_id,post_id(或any_id),以及布尔字段true或false.这样,如果同一用户再次尝试评级,您将查询此新表中是否存在该ID,如果该值在布尔字段中为真,则显示一条消息,告诉他无法评级.如果你想使用一个IP地址,这是可以的,但有时他会改变他的位置,他的网络,他的手机和IP也会改变.你也应该考虑这一点.而COOKIE并不是一个很好的解决方案.只需使用IP地址和附加表