peter-cooper
asked on
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
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;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you very much Ray.
You're welcome and thanks for the points. You might find this easier if you can get away from all the fiddly punctuation. Two things that can help you do that are HEREDOC notation and object notation. This script would be functionally equivalent to the snippet posted above, and IMHO would be much easier to type and read.
// IF THERE ARE ROWS FROM THE QUERY
if (mysql_num_rows($result1) > 0)
{
// SET UP VARIABLES FOR OUR BROWSER OUTPUT
$msgread = NULL;
$datenow = date('d/m/Y');
// RETRIEVE THE ROWS INTO A ROW OBJECT
while($row = mysql_fetch_obj($result1))
{
// FORMAT THE OUTPUT WITH HEREDOC NOTATION
$row = <<<EOD
<FONT COLOR='1d99f0'><b>$row->to_user</b></font>
<p />
$datenow
<p />
$row->message
<p />
$row->from_user
EOD;
// CONCATENATE THE ROW TO THE OUTPUT DOCUMENT
$msgread .= $row . PHP_EOL;
}
// AFTER ALL ROWS ARE FORMATTED
echo $msgread;
}
You'll also want to get off MySQL as soon as possible. PHP is doing away with MySQL support. The reasons for this, and the alternatives that can help you keep your web site working, are documented in this article.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html