【发布时间】:2012-04-27 00:57:11
【问题描述】:
我用 PHP 创建了一个简单的站点,用户可以在其中提交博客,而其他用户(已登录)可以在上面发布 cmets。我在每个博客下方创建了一个名为“cmets”的链接,单击该链接将显示/隐藏与特定博客相关的所有 cmets(如果用户已登录,它将显示一个表单字段,他们可以在其中提交新的 cmets) .所以基本上每个博客都会有多个cmet。我为此做了两个不同的代码,但它们都有相同的问题,即每个评论出现两次(其他一切正常)。谁能指出原因?
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);
//第二个版本的内循环://
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);
【问题讨论】:
-
请检查您的第二个查询:
select * from blog, blogcomment where $a=blogID您正在连接两个表,但未指定导致cross join(en.wikipedia.org/wiki/Join_(SQL)#Cross_join) 的关系