Jump to content


Photo

while(forever)


  • Please log in to reply
3 replies to this topic

#1 tleisher

tleisher
  • Members
  • PipPipPip
  • Advanced Member
  • 88 posts

Posted 05 September 2006 - 11:25 PM

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

$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"];
}

It echos properly, but it goes on forever.

#2 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 05 September 2006 - 11:38 PM

if its selecting 1 record from the database, then thiers no need to use a while loop. This is fine:
$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"];


Also the correct syntax is this:
while ($comment = mysql_fetch_array($com))
Otherwise it'll go into a never ending loop.

#3 tleisher

tleisher
  • Members
  • PipPipPip
  • Advanced Member
  • 88 posts

Posted 05 September 2006 - 11:44 PM

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.

#4 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,021 posts

Posted 06 September 2006 - 12:49 AM

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
$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;

}

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users