从while循环创建单个变量

时间:2014-09-20 11:01:14

标签: php mysql

我正在尝试将一个while循环放入一个可以用作单个echo的变量中。发生的事情是循环只显示第一条记录。

所有数据库连接都已到位并已连接。如果有人可以指出我的错误,我将不胜感激。非常感谢

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

3 个答案:

答案 0 :(得分:1)

你将每个循环覆盖它,它应该是.=

$msgread = "";

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

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

应该像:

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

}

答案 1 :(得分:1)

在while循环的第一行使用.
$msgread .= "<FONT COLOR='1d99f0'>" . "<b>" . $row['to_user'] . "</b>" . "</font>";

答案 2 :(得分:0)

您在.

行上错过了$msgread = "<FONT COLOR='1d99f0'>" . "<b>" . $row['to_user'] . "</b>" . "</font>";

这将是$msgread .= "<FONT COLOR='1d99f0'>" . "<b>" . $row['to_user'] . "</b>" . "</font>";