要在 PHP 和 MySQL 中限制用户对每个帖子只能发表一个评论,您可以结合使用 cmets 表上的唯一约束和检查 insertComment() 方法中是否存在评论。
首先,您可以在 cmets 表上添加唯一约束,以防止具有相同用户 ID 和帖子 ID 的重复条目。这可以使用以下 SQL 语句完成:
ALTER TABLE comments
ADD UNIQUE (user_id, post_id);
该语句将对 cmets 表中的 user_id 和 post_id 列添加唯一约束。这意味着任何具有相同 user_id 和 post_id 值的后续插入都将失败。
接下来,您可以修改 insertComment() 方法以在插入评论之前检查是否存在具有给定 user_id 和 post_id 值的评论。您可以通过添加一个 SELECT 查询来检查是否存在具有相同 user_id 和 post_id 的评论,并且只有在不存在时才插入评论。以下是如何执行此操作的示例:
public function insertComment($user_id, $id, $comment)
{
// Check if a comment with the same user_id and post_id already exists
$checkSql = "SELECT * FROM comments
WHERE user_id = :user_id AND post_id = :id";
$checkStmt = parent::connect()->prepare($checkSql);
$checkStmt->execute(["user_id" => $user_id, "id" => $id]);
$commentExists = $checkStmt->fetch();
if ($commentExists) {
// If a comment already exists, return an error message
return "You have already commented on this post!";
} else {
// If a comment does not exist, insert the comment
$sql = "INSERT INTO comments(user_id, post_id, comment_content)
VALUES(:user_id, :id, :comment)";
$sqlArr = [
"user_id" => $user_id,
"id" => $id,
"comment" => $comment
];
$stmt = parent::connect()->prepare($sql);
if ($stmt->execute($sqlArr)) {
return "success";
} else {
return "error";
}
}
}
在此示例中,insertComment() 方法首先使用 SELECT 查询检查是否存在具有相同 user_id 和 post_id 值的评论。如果评论已经存在,则返回一条错误消息。否则,使用原始 INSERT 语句插入注释。
然后,您可以在代码中调用 insertComment() 方法来插入评论,并处理返回值以在用户已对帖子发表评论时显示错误消息。以下是如何执行此操作的示例:
// Call the insertComment() method
$result = insertComment($user_id, $id, $comment);
// Check the result and display an error message if necessary
if ($result === "You have already commented on this post!") {