Jump to content

Archived

This topic is now archived and is closed to further replies.

tleisher

while(forever)

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.

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites
Yep, that last part fixed it. Thanks.

Also the reason for a while loop is it will have more then one row in the future.

Share this post


Link to post
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]

Share this post


Link to post
Share on other sites

×

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.