Xiahao Wang Xiahao Wang - 1 month ago 7
HTML Question

echo an array from mysql and in a table with defined rows and cols

I have got an array from mysql, now I am trying to put it into a table with 4 columns using a while loop. My method is that when

$counter%4==0
, I echo
</tr>
so that every 4 items will be arranged in one row. But I can't get the result I want, so can anyone tell me where the problem is or offer me a better way to do this? Here is my code:

<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<?php

$query1 = "SELECT * FROM post WHERE post_status='New' AND post_type='Facilities' AND post_keywords='icon'";
$run1 = mysql_query($query1);

$counter=0;
while($row1 = mysql_fetch_array($run1)){

$post_id = $row1['post_id'];
$post_title = $row1['post_title'];
$post_date = $row1['post_date'];
$post_author = $row1['post_author'];
$post_keywords = $row1['post_keywords'];
$post_type =$row1['post_type'];

$post_content = $row1['post_content'];
$post_status =$row1['post_status'];

if($counter%4==0){
echo '<tr>';
}
?>
<td>//here is the content from the array
<div id="<?php echo $post_id?>" class="FacItem" onmousedown="function onmousedown() { fac_change('down','<?php echo $post_id?>') }" onmouseup="function onmouseup() { fac_change('up','<?php echo $post_id?>') }" onmouseover="function onmouseover() { fac_change('over','<?php echo $post_id?>') }" onmouseout="function onmouseout() { fac_change('out','<?php echo $post_id?>') }"><a href="?page_id=282"><?php echo $post_content?></a></div>
</td>

<?php
if($counter%4==0){
echo '</tr>';
}
$counter++;
}
?>
</tbody>
</table>

Answer

The problem is that you're opening and closing the row at the same round of the loop

you need to rearrange this code:

<?php
    if($counter%4==0)
    {
        echo '</tr>';
    }
    $counter++;

to

<?php
    $counter++;
    if($counter%4==0)
    {
        echo '</tr>';
    }

So now, when the counter is 0, an new row is started, and then it becomes 1 before the close row if statement is executed... then for every 4th value, the counter becomes 4 (or a multiple of 4) just before the close row, the close row if statement is executed.

Since the counter is still a multiple of 4 the next time the loop executes, an opening is made, but the counter becomes 1 after this, so no closing is called.

Example

Loop #    Counter at <tr> if stmt    Counter at </tr> if stmt
    1                0 <tr>               1
    2                1                    2
    3                2                    3    
    4                3                    4 </tr>
    5                4 <tr>               5
    6                5                    6
    7                6                    7    
    8                7                    8 </tr>                    
Comments