0

我用 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 .... &nbsp;&bull;&nbsp; $row[date] &nbsp;&bull;&nbsp; <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] &nbsp;&bull;&nbsp; $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); 

//第二个版本的内循环://

if ( isset ($_SESSION["gatekeeper"])) 
{
  while($sub = mysql_fetch_array($result2)) 
  { 
    echo "<p class='third' >$sub[commentdate] &nbsp;&bull;&nbsp; $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] &nbsp;&bull;&nbsp; $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);
4

1 回答 1

0

您的问题在于第一个示例中的此查询。

$result2 = mysql_query ("select * from blog, blogcomment where $a=blogID")

您已经查询了 blog 表,因此无需再次查询。只需将其更改为

$result2 = mysql_query ("select * from blogcomment where $a=blogID")

应该解决问题。

但是,您需要考虑很多事情。

  • 你为什么要重新发明轮子?那里有很多不错的博客应用程序。你最好使用其中之一。
  • 不建议再使用 mysql_ 系列函数。走开学习 mysqli_ 或更好的PDO
  • 您应该了解关注点分离。至少您应该确保您的数据访问/业务逻辑与您的显示逻辑是分开的。MVC在 PHP 中很常见。
  • 您还应该了解 JOIN。即使在这个简单的内联脚本中,您在循环中也有一个效率不高的查询。您可以将查询合并为一个(就像您尝试使用内部查询一样)。不同之处在于一个查询应该在您的主循环之外。
于 2012-04-15T11:25:27.713 回答