user1532468
user1532468

Reputation: 1753

Create single variable from while loop

I am trying to place a while loop into a variable that I can use as a single echo. What is happening is that the loop is only displaying the first record.

All db connections are in place and connected. I would appreciate it if someone could point out my error. Many thanks

if (mysql_num_rows($result1) >0) {
    $msgread = "";
    while($row = mysql_fetch_array($result1)) { 
        $msgread = "<FONT COLOR='1d99f0'>" . "<b>" . $row['to_user'] . "</b>" . "</font>";
        $msgread .= "<p />";
        $msgread .= date("d/m/Y");
        $msgread .= "<p />";
        $msgread .= $row['message'];
        $msgread .= "<p />";
        $msgread .= $row['from_user'];
    }

    $error1 = false;
}

if($error1 == 0)  {     
    echo $msgread;               
}

Upvotes: 0

Views: 55

Answers (3)

Avinash Babu
Avinash Babu

Reputation: 6252

You have missed . on the line $msgread = "<FONT COLOR='1d99f0'>" . "<b>" . $row['to_user'] . "</b>" . "</font>";

It would be $msgread .= "<FONT COLOR='1d99f0'>" . "<b>" . $row['to_user'] . "</b>" . "</font>";

Upvotes: 0

Kevin
Kevin

Reputation: 41885

You are overwriting it each loop, it should be .=:

$msgread = "";

while($row = mysql_fetch_array($result1)) {

   $msgread = "<FONT COLOR='1d99f0'>" . "<b>" . $row['to_user'] . "</b>" . "</font>";
            ^^ it gets overwritten each loop

Should be like:

if (mysql_num_rows($result1) >0) {

    $msgread = ""; // initialize

    while($row = mysql_fetch_assoc($result1)) {

        $msgread .= "<FONT COLOR='1d99f0'><b>" . $row['to_user'] . "</b></font>";
              // ^ concatenation
        $msgread .= "<p>" . date("d/m/Y") . '</p>';
        $msgread .= "<p>" . $row['message'] . '</p>';
        $msgread .= "<p>" . $row['from_user'] . '</p>';           
    }

    echo $msgread; // then echo

}

Upvotes: 1

Salini L
Salini L

Reputation: 879

Use . in the while loop's first line
$msgread .= "<FONT COLOR='1d99f0'>" . "<b>" . $row['to_user'] . "</b>" . "</font>";

Upvotes: 1

Related Questions