我已经在我的网站上创建了评论功能。我想为它添加一个回复功能,但我不知道该怎么做。
我可以在网站上发表评论并检索它们。
我想做一个回复功能,它使用它的“父母”ID显示在它下面。
期望的输出:
- 第一条评论
- 第一次回复
- 第二次回复
- 第二条评论
醇>
- 第一次回复
- 第二次回复
我的程序如下:
<html>
<form action="" method ="POST">
Namn: <br>
<input type="text" name ="name"><br>
Kommentar: <br>
<textarea name="comment" rows="10" cols="20"> </textarea><br>
<input type ="submit" name ="submit" value="Skicka">
</form>
</html>
connectDB
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'com';
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die(mysqli_error($connect));
?>
getComments
<?php
include ('connectDB.php');
if($connect){
mysqli_select_db($connect, "comments");
$query2 = "SELECT * FROM data ORDER BY `id` DESC";
$result = mysqli_query($connect, $query2);
$comments = array();
while($row = mysqli_fetch_array($result)){
$name = $row['Name'];
$comment = $row['Comment'];
$date = $row['Date'];
echo "
<div style='width:60%' class='col-lg-12'>
<div class='panel panel-default'>
<div class='panel-heading'>
<strong> $name </strong><span style='float:right'class='text-muted'>$date</span>
</div>
<div class='panel-body'>$comment
</div>
</div><!-- /panel panel-default -->
</div><!-- /col-sm-5 -->";
}
}
?>
StoreComments
<?php
if(isset($_POST['submit'])){
$name = htmlentities($_POST['name']);
$comment = htmlentities($_POST['comment']);
$date = date("Y-m-d");
$connect = mysqli_connect("localhost", "root", "");
if($connect){
mysqli_select_db($connect, "comments");
$query = "INSERT INTO data(Name, Comment, Date) VALUES (\"" . $name . "\", \"" . $comment . "\", \"" . $date . "\")";
if(mysqli_query($connect, $query)){
} else {
die ("Failed: " . mysqli_error($connect));
}
} else {
die("Failed to connect to mysql: " . mysqli_errno($connect));
}
}
}
?>
答案 0 :(得分:0)
为了防止N + 1查询问题,当您为每个评论创建另一个查询以查找回复时,您可以使用嵌套集模型策略,如本主题中所述:{{3 }}
请参阅有关php / Mysql best tree structure。
的帖子<强> [UPDATE] 强>
如果您不关心性能,可以按照此主题解决方案进行操作:Managing Hierarchical Data in MySQL