是否有任何方法可以防止用户多次点击而不将其插入数据库?
我知道我可以禁用该按钮,但我想在不重新加载页面的情况下完成所有操作。
$dbh = mysqli_connect("localhost", "root", "", "testdb");
$postid = $_POST['postid'];
if(isset($_POST['liked'])&& empty($_SESSION[$postid])){
$_SESSION[$postid] = TRUE;
$userid = $_SESSION['username'];
$result = mysqli_query($dbh,"SELECT * FROM user_images WHERE id=$postid");
$row = mysqli_fetch_array($result);
$n = $row['likes'];
mysqli_query($dbh,"INSERT INTO likes(username, postid) VALUES('$userid', '$postid')");
mysqli_query($dbh,"UPDATE user_images SET likes=$n+1 WHERE id=$postid");
echo $n+1;
exit();
}
if (isset($_POST['unliked'])){
$postid = $_POST['postid'];
$result = mysqli_query($dbh,"SELECT * FROM user_images WHERE id=$postid");
$row = mysqli_fetch_array($result);
$n = $row['likes'];
$userid = $_SESSION['username'];
//delete from likes before updating
mysqli_query($dbh,"DELETE FROM likes WHERE postid=$postid AND username=$userid");
mysqli_query($dbh,"UPDATE user_images SET likes=$n-1 WHERE id=$postid");
echo $n-1;
exit();
}
答案 0 :(得分:0)
if(isset($_POST['liked'])){
$postid = $_POST['postid'];
$userid = $_SESSION['username'];
$result = mysqli_query($dbh,"SELECT * FROM user_images WHERE id=$postid");
$row = mysqli_fetch_array($result);
$n = $row['likes'];
$check_query = mysqli_query($dbh,"SELECT * FROM likes WHERE username = '$userid' AND postid = '$postid'");
$found = mysqli_num_rows($check_query);
if ($found == 0) {
mysqli_query($dbh,"INSERT INTO likes(username, postid) VALUES('$userid', '$postid')");
mysqli_query($dbh,"UPDATE user_images SET likes=$n+1 WHERE id=$postid");
echo $n+1;
}
exit();
}
答案 1 :(得分:0)
首先,您需要在表中创建unique index,以确保即使您的PHP代码中存在错误,也不允许重复条目。由于用户可以喜欢多个帖子,因此您必须使用两列创建索引:
create unique index IDU_likes on likes (username,postid);
然后你必须修改你的代码并检查插入是否失败(你应该这样做总是)。此外,您使用的代码向SQL injection开放,您应该使用prepared statements和bind the variables而不是手动构建查询,例如:
$stmt=mysqli_prepare($dbh,"INSERT INTO likes(username, postid) VALUES(?, ?)");
mysqli_stmt_bind_param($stmt,'si',$userid,$postid);
if(mysqli_stmt_execute($stmt) {
$n=$n+1;
$stmt=mysqli_prepare($dbh,"UPDATE user_images SET likes=? WHERE id=?");
mysqli_stmt_bind_param($stmt,'ii',$n,$postid);
mysqli_stmt_execute($stmt)
}
echo $n;