tleisher Posted September 5, 2006 Share Posted September 5, 2006 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. Quote Link to comment https://forums.phpfreaks.com/topic/19833-whileforever/ Share on other sites More sharing options...
wildteen88 Posted September 5, 2006 Share Posted September 5, 2006 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. Quote Link to comment https://forums.phpfreaks.com/topic/19833-whileforever/#findComment-86782 Share on other sites More sharing options...
tleisher Posted September 5, 2006 Author Share Posted September 5, 2006 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. Quote Link to comment https://forums.phpfreaks.com/topic/19833-whileforever/#findComment-86789 Share on other sites More sharing options...
Barand Posted September 6, 2006 Share Posted September 6, 2006 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] Quote Link to comment https://forums.phpfreaks.com/topic/19833-whileforever/#findComment-86815 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.