Jump to content

[SOLVED] while loop within a function


razta

Recommended Posts

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

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!  :D

 

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

Archived

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

×
×
  • 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.