我正在处理的网站允许用户向网站发布多条评论,每条评论都有一个在数据库中自动增加的唯一ID。然后我将这些id设置为注释对象列表。在我的html中,我然后检索这些id并为每个注释对象创建一组喜欢和不喜欢的按钮(带有foreach循环)。
我遇到的问题是,当用户点击类似按钮时,该按钮的名称也与其id(动态名称)的名称相同,应该与其中的id进行比较数据库。但是,单击按钮只会更改屏幕上显示的其中一条评论的相似内容。我目前正在使用会话来存储数组并将其值发送到DA类,但没有取得任何成功。
我不确定如何正确发送和比较名称与数据库中的ID。
html:
<?php foreach ($comments->getComments() as $comment) : ?>
<!--The like button:-->
<form class="userActions" action="../Controller/index.php" method="post">
<input type="submit" name="<?php echo "comment_#" . $comment->getID() . "_Likes"; ?>" class="btnLike btnLikeStyle like" value="Like">
<input type="hidden" name="action" value="comment_like">
</form>
<!--Show number of likes on the page:-->
<div>
<!--display the likes number from the database-->
<label class="lblLikes"><?php echo htmlspecialchars($comment->getLikes()); ?></label>
</div>
<!--Dislike button:-->
<form class="userActions" action="../Controller/index.php" method="post">
<input type="submit" name="<?php echo "comment_#" . $comment->getID() . "_Likes"; ?>" class="btnDislike btnDislikeStyle dislike" value="Dislike">
<input type="hidden" name="action" value="comment_dislike">
</form>
<?php endforeach; ?>
控制器:
case 'comment_like':
$commentID = $comment->getID();
$comments = comments::addLike($theCommentID);
include('../View/home.php');
break;
case 'comment_dislike':
$commentID = $comment->getID();
$comments = comments::addDislike($theCommentID);
include('../View/home.php');
break;
评论类
function addLike($commentID) {
CommentDA::addCommentLike($commentID);
}
function addDislike($commentID) {
CommentDA::addCommentDislike($commentID);
}
DA类:
public static function addCommentLike($commentID) {
$db = self::getConnection();
$query = 'UPDATE comments
SET commentLikes = CommentLikes + 1
WHERE CommentID = :commentIDPlaceholder';
$statement = $db->prepare($query);
$statement->bindValue(':commentIDPlaceholder', $commentID);
try {
$statement->execute();
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
$statement->closeCursor();
}
public static function addCommentLike($commentID) {
$db = self::getConnection();
$query = 'UPDATE comments
SET commentLikes = CommentLikes - 1
WHERE CommentID = :commentIDPlaceholder';
$statement = $db->prepare($query);
$statement->bindValue(':commentIDPlaceholder', $commentID);
try {
$statement->execute();
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
$statement->closeCursor();
}
答案 0 :(得分:0)
按钮示例..
<label for="like_button">
<div
<?php
if($like_status == "liked")
{
echo'class="liked_class"';
}else
{
echo 'class="empty_class"';
};
?>
><input type="radio" id="liked" name="like_status" value="like_button" form="form01"
<?php
if ($like_status == "liked")echo "checked";
?>
> Like button content
</div></label>
您可以将不透明度设置为0或将单选按钮的位置移动到远处以隐藏它。 (Hide radio button while keeping its functionality)