如何为特定帖子制作评论系统并检索它?

问题描述 投票:0回答:1

我正在为网站制作问答系统。我在这里遇到问题。我想让用户为每个帖子添加特定的评论。我制作的脚本与Quora.com类似,所以你可以理解我的脚本是如何工作的...这就是我的评论表的样子,请看一下图片。如何为每个帖子添加特定评论?

    //code for insert comments to the tables 
    function setComments($connection) {
        if (isset($_POST['commentSubmit'])) {
            $uid = $_POST['uid'];
            $date = $_POST['date'];
            $message = $_POST['message'];

            //sql connection 
            $sql = "INSERT INTO comments (uid,date,message) VALUES ('$uid','$date','$message')";
            $result = $connection ->query($sql);
        }
    }
    //function for get comments from the databse 
    function getComments($connection) {
        $sql = "SELECT * FROM comments";
        $result = $connection ->query($sql);
        while($row = $result->fetch_assoc()) {
            //showing records 
            echo '<div id="comment_box">';
            echo $row['uid'].'<br>';
            //echo $row['cid'].'<br>';
            echo nl2br($row['message']).'<br>';
            echo $row['date'];
            echo '</div>';
            echo '<hr>';
        }
    }

我在这里做了两个函数setComments用于插入注释 其他功能适用于getComments

更新

此问题表用于提问,因此用户可以提出问题。

this is question table

php mysql database
1个回答
1
投票

您只需在评论表中使用post_id,以便每条评论都与特定帖子相关。并宣布它为foreign key

然后,两个函数set_commentsget_comments都应该有一个post_id参数,该参数将被插入到注释表中并查询特定帖子的那些注释:

INSERT INTO comments (uid,date,message, post_id) VALUES ('$uid','$date','$message', '$post_id');

之后,使用此post_id,您可以通过此ID在特定帖子下查询这些评论。

请注意:尝试使用prepared statements代替数据库操作。


更新:

您应添加为外键的列应具有与原始表中的列完全相同的数据类型。

所以,假设你有一个问题表,Id为整数。然后,您应该添加到comments表的外键列应如下所示:

ALTER TABLE comments ADD question_id INT NOT NULL;
ALTER TABLE comments ADD CONSTRAINT fk_question_id FOREIGN KEY (question_id) REFERENCES questions(id);
© www.soinside.com 2019 - 2024. All rights reserved.