Reputation: 201
I have a mySQL database, and I'm using PHP to grab it and display it in a HTML table. It's set up like this:
<table>
<tr>
<td>Title 1</td>
<td>Title 2</td>
</tr>
<?php
$i=0;
while ($i < $num) {
$col1=mysql_result($result,$i,"col1");
$col2=mysql_result($result,$i,"col2");
?>
<tr>
<td><?php echo $col1; ?></td>
<td><?php echo $col2; ?></td>
</tr>
</table>
<?php
$i++;
echo '<br />';
}
?>
The problem: for the first set of data it pulls, the columns align with the titles. But for every repeating row after that, the columns are separated by one space, and don't align with their titles. It looks like this:
Title 1 Title 2
col1 col2
col1 col2
col1 col2
Sorry if the wording is confusing.
Upvotes: 0
Views: 127
Reputation: 122
As mentioned by others. Your table was closing inside of your loop. I pulled all of the PHP code together to help avoid confusion with the loop.
<table>
<tr>
<td>Title 1</td>
<td>Title 2</td>
</tr>
<?php
$num = $mysql_result->num_rows;
for($i = 0; $i < $num; $i++) {
$row = $mysql_result->fetch_assoc();
echo '<tr>\n';
echo '<td>'.$row['col1'].'</td>\n';
echo '<td>'.$row['col2'].'</td>\n';
echo '</tr>\n';
echo '<br />';
}
?>
</table>
Upvotes: 0
Reputation: 33512
You are closing the table inside the loop. You need to close it after you have finished it.
<table>
<tr>
<td>Title 1</td>
<td>Title 2</td>
</tr>
<?php
$i=0;
while ($i < $num)
{
$col1=mysql_result($result,$i,"col1");
$col2=mysql_result($result,$i,"col2");
?>
<tr>
<td><?php echo $col1; ?></td>
<td><?php echo $col2; ?></td>
</tr>
<?php
$i++;
echo '<br />';
}
?>
</table>
For extra clarity, the first row worked as you expected as you hadn't closed the table yet.
Given that the other table info as being posted without an opening <table>
tag, you would think that it wouldn't display at all - but most browsers these days will try to correct HTML on the fly, so certain things (like missing table tags when opening) are displayed as if there was one right in front of it.
Upvotes: 0
Reputation: 15229
You're closing the table inside the loop, try to pull the </table>
outside of the loop.
Upvotes: 2
Reputation: 207901
Move the </table>
to be after your last block of PHP. You're repeatedly closing the table when you just want to loop and create new rows. Save the closing of the table until after you while loop is done.
Upvotes: 0