0

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;               
}
6
  • You have a closing bracket at the end of the msgread attribution. Identation matters here, don't avoid it. Could it be that? Commented Sep 20, 2014 at 11:03
  • Does your DB query return more than 1 record? Commented Sep 20, 2014 at 11:03
  • You can store them in array and than run the foreach loop? if its ok Commented Sep 20, 2014 at 11:03
  • db query returns all records. Do you have example arif. Thanks Commented Sep 20, 2014 at 11:11
  • can you show the format you want ? Commented Sep 20, 2014 at 11:14

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.