我用PHP创建了一个简单的网站,用户可以在其中提交博客,其他用户(已登录)可以在上面发表评论。我在每个博客下方制作了一个名为"评论"的链接,单击该链接时将显示/隐藏与特定博客相关的所有评论(如果用户已登录,它将显示一个表单字段,他们可以在其中提交新评论)。所以基本上每个博客都会有多个评论。我为此做了两个不同的代码,但它们都有相同的问题,每个评论出现两次(其他一切正常)。谁能指出为什么?
mysql_select_db ("ooze");
$result = mysql_query ("select * from blog") or die(mysql_error());
$i = 1;
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • <a href='#' onclick='"toggle_visibility('something$i'); return false'">Comments</a><div id='something$i' style='display: none;'>";
$i++;
$a = $row["ID"];
$result2 = mysql_query ("select * from blog, blogcomment where $a=blogID") or die(mysql_error());
while($sub = mysql_fetch_array($result2))
{
echo "<p class='third' >$sub[commentdate] • $sub[username]</p><p>said:</p> <p>$sub[comment]</p>";
}
if ( isset ($_SESSION["gatekeeper"]))
{
echo '<form method="post" name="result_'.$row["ID"].'" action="postcomment.php"><input name="ID" type = "hidden" value = "'.$row["ID"].'" /><input name="comment" id="comment" type="text" style="margin-left:20px;"/><input type="submit" value="Add comment" /></form>';
}
else
{
echo '<p class="third"><a href="register.html">Signup </a>to post a comment</p>';
}
echo "</div>";
}
mysql_close($conn);
内 loop://的第二个版本
if ( isset ($_SESSION["gatekeeper"]))
{
while($sub = mysql_fetch_array($result2))
{
echo "<p class='third' >$sub[commentdate] • $sub[username] said:</p> <p>$sub[comment]</p>";
}
echo '<form method="post" name="result_'.$row["ID"].'" action="postcomment.php"><input name="ID" type = "hidden" value = "'.$row["ID"].'" /><input name="comment" id="comment" type="text" style="margin-left:20px;"/><input type="submit" value="Add comment" /></form>';
}
else
{
while($sub = mysql_fetch_array($result2))
{
echo "<p class='third' >$sub[commentdate] • $sub[username] said:</p> <p>$sub[comment]</p>";
}
echo '<p class="third"><a href="register.html">Signup </a>to post a comment</p>';
}
echo "</div>";
}
mysql_close($conn);
您的问题在于第一个示例中的此查询。
$result2 = mysql_query ("select * from blog, blogcomment where $a=blogID")
您已经查询了博客表,因此无需再次查询它。只需将其更改为
$result2 = mysql_query ("select * from blogcomment where $a=blogID")
应该解决问题。
但是,您需要考虑很多事情。
- 你为什么要重新发明轮子?那里有很多好的博客应用程序。你最好使用其中之一。
- 建议不再使用 mysql_ 系列函数。走开,学习mysqli_或更好的PDO。
- 您应该了解关注点分离。至少,您应该确保数据访问/业务逻辑与显示逻辑分开。MVC在PHP中很常见。
- 您还应该了解 JOIN。即使在这个简单的内联脚本中,您也可以在循环中有一个查询,这不是很有效。您可以将查询合并为一个(就像您尝试使用内部查询一样)。不同之处在于一个查询应该在你的主循环之外。