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

 

Link to comment
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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