Jump to content

while(forever)


tleisher

Recommended Posts

Why does this While loop go on forever, there is only 1 entry in the table that its accessing.

[code=php:0]
$com = mysql_query("SELECT * FROM `comments` WHERE `attraction` = '{$id}'") or die(mysql_error());
$comments = mysql_fetch_array($com);
while ($comment = $comments)
{
         $username = mysql_query("SELECT `username` FROM `users` WHERE `id` = '{$comment["userid"]}'") or die(mysql_error());
         $username = mysql_fetch_array($username);
         echo "<b>Posted by:</b> " . $username["username"];
         echo "<br /><b>Comment:</b> " . $comment["comment"];
}[/code]

It echos properly, but it goes on forever.
Link to comment
Share on other sites

if its selecting 1 record from the database, then thiers no need to use a while loop. This is fine:
[code=php:0]$com = mysql_query("SELECT * FROM `comments` WHERE `attraction` = '{$id}'") or die(mysql_error());

$comment = mysql_fetch_array($com);
$username = mysql_query("SELECT `username` FROM `users` WHERE `id` = '" . $comment['userid'] . "'") or die(mysql_error());

$username = mysql_fetch_array($username);

echo "<b>Posted by:</b> " . $username["username"];
echo "<br /><b>Comment:</b> " . $comment["comment"];[/code]


Also the correct syntax is this:
[code=php:0]while ($comment = mysql_fetch_array($com)) [/code]
Otherwise it'll go into a never ending loop.
Link to comment
Share on other sites

while ($comment = $comments)

You are using an assignment (=) and not a comparison (==) so as it is always 'true' it goes on forever. Just as though you had put

while (1)


Also, if you are getting a value from 1 table and using that in the WHERE clause of another query it is better to use a single query with a JOIN.  eg
[code]$sql = "SELECT c.comment, u.username
        FROM comments c INNER JOIN users u ON u.id = c.userid
        WHERE c.attraction = '$id' ";
$res = mysql_query($sql) or die(mysql_error());
while (list ($comment, $username) = mysql_fetch_row($res)) {
        echo "<b>Posted by:</b> " . $username;
        echo "<br /><b>Comment:</b> " . $comment;

}[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.