在 PHP 中对特定帖子发表评论


Place a comment on a specific post in PHP

我正在为学校做一个项目,它与Instagram有些相似。因此,您可以在时间线上发布照片,然后其他用户可以对此照片发表评论。

此注释选项已成功完成:您可以放置注释,注释就会进入数据库。

注释类:PHP 代码

public function __set($p_sProperty, $p_vValue)
{
    switch($p_sProperty)
    {
        case "Comment":
            $this->m_sComment = $p_vValue;
            break;
    }      
}
public function __get($p_sProperty)
{
    $vResult = null;
    switch($p_sProperty)
    {
    case "Comment": 
        $vResult = $this->m_sComment;
        break;
    }
    return $vResult;
}

    public function Save() {
        $conn = Db::getInstance();
        //$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $statement = $conn->prepare('INSERT INTO comment(comment, postID, userID) VALUES(:comment)');
        $statement->bindValue(':comment', $this->Comment);
        $statement->execute();
    }
    public function GetRecentActivities($p_iPostID) {
        $conn = Db::getInstance();
        $allComments = $conn->query("SELECT * FROM comment ORDER BY id DESC;");
        return $allComments;
    }
}

但现在的问题是:*现在对照片的评论出现在每个帖子上,而不是在特定帖子上? 在帖子的URL中,我发送了一个特定的POSTID。 https://i.stack.imgur.com/IkJGL.png我怎样才能只在具有正确 POSTID 的帖子上发表评论?

在答案中,我假设您使用GetRecentActivities来获取帖子的评论。

我注意到您没有在数据库中设置postID字段,这是为什么?postID字段将帮助您将帖子映射到评论。没有它,您(和 SQL)无法确定编写注释的上下文。我相信您知道如何在您提供的INSERT语句中添加postID,但供参考:

$stmt = $conn->prepare("INSERT INTO comments (comment, postID) VALUES (:comment, :postID)");
$stmt->bindValue(':comment', $this->Comment);
$stmt->bindValue(':postID', $this->PostID);
$stmt->execute();

在调用SELECT * FROM comment ORDER BY id DESC;的 SQL 中,可以添加 WHERE 子句来"过滤"返回的数据。在您的情况下,这将是语法:

SELECT * FROM comment WHERE postID = <post_id> ORDER BY id DESC;

有关您可以在SELECT声明中传递的内容的更多信息,请访问 http://dev.mysql.com/doc/refman/5.7/en/select.html