razta Posted August 27, 2009 Share Posted August 27, 2009 Hello, Im having a little trouble with the following: function Guestbook(){ $query = "SELECT name, comment FROM guestbook"; $result = mysql_query($query); while($row = mysql_fetch_array($result, MYSQL_ASSOC)){ return "<b>Name</b> : {$row['name']} <br>" . "<b>Message</b> : {$row['comment']} <br><br>"; } } When I call the Guestbook() function it only returns one comment and omits the rest. I have been playing with the code for hours, im sure theres a simple solution. Thanks in advance! Link to comment https://forums.phpfreaks.com/topic/172058-solved-while-loop-within-a-function/ Share on other sites More sharing options...
roopurt18 Posted August 27, 2009 Share Posted August 27, 2009 return causes the function to end immediately. You need to build the list of results inside the function and issue return after the list is built. Link to comment https://forums.phpfreaks.com/topic/172058-solved-while-loop-within-a-function/#findComment-907211 Share on other sites More sharing options...
razta Posted August 27, 2009 Author Share Posted August 27, 2009 Thank you for the reply roopurt18. I think im on the right track however theres still something im missing. function Guestbook(){ $query = "SELECT name, comment FROM guestbook"; $result = mysql_query($query); while($row = mysql_fetch_row($result)){ $name = $row[0]; $comment = $row[1]; } return "<b>Name</b> : {$name} <br>" . "<b>Message</b> : {$comment} <br><br>"; } Should I also stick the return in a loop?! Thanks again! Link to comment https://forums.phpfreaks.com/topic/172058-solved-while-loop-within-a-function/#findComment-907226 Share on other sites More sharing options...
akitchin Posted August 27, 2009 Share Posted August 27, 2009 no - you still need to construct the message list within the while() loop. what roopurt meant was that you return this string AFTER constructing it: function Guestbook(){ $guestbook = ''; $query = "SELECT name, comment FROM guestbook"; $result = mysql_query($query); while($row = mysql_fetch_row($result)){ $name = $row[0]; $comment = $row[1]; $guestbook .= "<b>Name</b> : {$name} <br>" . "<b>Message</b> : {$comment} <br><br>"; } return $guestbook; } Link to comment https://forums.phpfreaks.com/topic/172058-solved-while-loop-within-a-function/#findComment-907230 Share on other sites More sharing options...
razta Posted August 27, 2009 Author Share Posted August 27, 2009 Works great!! Thanks to everyone for the help! Link to comment https://forums.phpfreaks.com/topic/172058-solved-while-loop-within-a-function/#findComment-907451 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.