Loop results executing twice
Posted
by
ozzysmith
on Stack Overflow
See other posts from Stack Overflow
or by ozzysmith
Published on 2012-04-15T11:16:17Z
Indexed on
2012/04/15
11:29 UTC
Read the original article
Hit count: 197
I creating a simple site with PHP where the users can submit blogs and other users (who are logged in) can post comments on them. I have made a link called "comments" below each blog that when clicked will show / hide all the comments relevant to the specific blog (also if the user is logged in, it will show a form field in which they can submit new comments). So basically each blog will have multiple comments. I have done two different codes for this but they both have the same problem that each comment appears twice (everything else works fine). Could anyone point out why?
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);
//second version of inner 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);
© Stack Overflow or respective owner