我对PHP和SQL比较陌生,而且我正在为自己的页面创建一个简单的博客工具,而且我仍然坚持如何制作评论部分。 我有2张桌子 general,其中包含博客文章和其他信息 评论,其中包含评论
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "blog";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die ("connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM general WHERE hidden = 'false' ORDER BY id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0){
while ($row = $result->fetch_assoc()){
echo "<div class='blogpost'>
<div class='blogbody'></div>";
//I need to do a query into the comments table at this point to find
//all comments matching the criteria to be matched with the post here.
echo "<div class='comments'></div></div>";
}
}
else{
echo "no posts";
}
我设法让博客文章正常工作,但是一旦我通过添加
尝试第二次查询$conn2 = new mysqli($servername, $username, $password, $dbname);
if ($conn2->connect_error){
die ("connection failed: " . $conn2->connect_error);
}
$sql2 = "SELECT * FROM comments WHERE $row["parent"] ORDER BY id DESC";
$result2 = $conn2->query($sql2);
if ($result2->num_rows > 0){
while ($row2 = $result2->fetch_assoc()){
}
}
else{
echo "no comments";
}
一切都好了。在开始加载其他帖子之前,我无法引入一个获取特定帖子所有评论的循环。
我将如何继续解决这个问题?我可能需要在任何代码示例中添加一些带有注释的勺子,
答案 0 :(得分:0)
您可以使用帖子的主键,并且可以在评论表中将其用作外键,这样您就可以轻松地使用该键来显示针对该特定帖子的所有评论。然后查询将是这样的:
$postid=$row['post_id'];
$ sql2 =“SELECT * FROM comments WHERE post_id ='$ postid'ORDER BY post_id DESC”;
答案 1 :(得分:0)
更改第二个查询以解决问题。
WHERE $row["parent"] ORDER. Change that to WHERE parent={$row['parent']} ORDER
感谢Jeff提供此答案