dystopia
dystopia

Reputation: 93

While loop only displaying 1 result in HTML

I've seen this question asked on this site, but mine has a slight variance that I haven't seen answered. My code looks like this

$sql_broadcast = mysql_query("SELECT id, mem_id, bc, bc_date FROM bc WHERE 
mem_id='$id' ORDER BY bc_date DESC LIMIT 50");
while($row = mysql_fetch_array($sql_broadcast)){
$mem_id = $row['mem_id'];
$bc = $row['bc'];
$bc_date = $row['bc_date'];
$bc_date = strftime("%b %d, %Y", strtotime($row['bc_date']));
$bc_display = '<table width="90%" align="center" cellpadding="4">
<tr>
<td width="93%">' .$bc_date. '<br />' .$bc. '</td>
</tr>
</table>';
}

?>

If I simply echo or print the table the loop works perfectly. However, I want to be able to print $bc_display inside the html page and when I do it that way only one result gets retrieved. I'm stumped, I've researched every thread that has been suggested and I'm still stumped. Thank you for the help!

Upvotes: 2

Views: 649

Answers (2)

KilZone
KilZone

Reputation: 1615

You are overwriting $bc_display on every iteration (removing the previous stored result / row), you have to to do something like this:

$bc_display .= '<table width="90%" align="center" cellpadding="4">
                  <tr>
                    <td width="93%">' .$bc_date. '<br />' .$bc. '</td>
                  </tr>
                </table>';

Make sure you set $bc_display to 'nothing' first ($bc_display = ''; on the first line of your code). *Also, you are creating a lot of tables, maybe this is a better alternative (though not what you asked):

$bc_display = '<table width="90%" align="center" cellpadding="4">';
// your query;
while($row = mysql_fetch_array($sql_broadcast))
{
    // First 5 lines of your while loop;
    $bc_display .= '<tr><td width="93%">' .$bc_date. '<br />' .$bc. '</td></tr>';
}
$bc_display .= '</table>';

This will create only one table, with multiple rows instead of multiple tables having one row. This is better markup language, but not required.

Upvotes: 1

Repox
Repox

Reputation: 15476

You have to concat your $bc_display string with .=

Like this:

$bc_display = '';
$sql_broadcast = mysql_query("SELECT id, mem_id, bc, bc_date FROM bc WHERE 
mem_id='$id' ORDER BY bc_date DESC LIMIT 50");
while($row = mysql_fetch_array($sql_broadcast)){
$mem_id = $row['mem_id'];
$bc = $row['bc'];
$bc_date = $row['bc_date'];
$bc_date = strftime("%b %d, %Y", strtotime($row['bc_date']));
$bc_display .= '<table width="90%" align="center" cellpadding="4">
<tr>
<td width="93%">' .$bc_date. '<br />' .$bc. '</td>
</tr>
</table>';
}

?>

Upvotes: 2

Related Questions