user1078385 user1078385 - 2 months ago 15
MySQL Question

mysql into table alternating <td>

I have a table which is being populated using mysql

<?php $sql = mysqli_query($con, "SELECT * FROM itemList"); ?>

<table>
<?php while($row=mysqli_fetch_assoc($sql)){ ?>
<tr>
<td>
<?php echo $row['item'] . ": <input type=\"checkbox\" name=\"cart[]\"
value=\"" . $row['item'] . "\">";?>
</td>
<td>
<?php echo $row['item'] . ": <input type=\"checkbox\" name=\"cart[]\"
value=\"" . $row['item'] . "\">";?>
</td>
</tr>
<?php
} ?>
</table>


Currently this code loops the same data into both column in the table. How would I got about to make the data loop into alternate columns?

For example:

<table>
<tr>
<td>
item1
</td>

<td>
item2
</td>
</tr>
<tr>
<td>
item3
</td>

<td>
item4
</td>
</tr>
</table>

Answer Source

try this

<?php $sql = mysqli_query($con, "SELECT * FROM itemList"); ?>

<table>
<tr>
<?php  $i=1; while($row=mysqli_fetch_assoc($sql)){ ?>

<td>
    <?php echo $row['item'] . ": <input type=\"checkbox\" name=\"cart[]\"
      value=\"" . $row['item'] . "\">";?>
</td>

<?php if($i%2 == 0){ echo "</tr><tr>";  } ?>

<?php $i++;
} ?>
</tr>
</table>

Other way as per @OlivierH comments on my above anwser

<?php 
$rows = array(); while($row=mysqli_fetch_assoc($sql)){
 $rows[] = $row;
} 
?>

<table>
<?php $totalrows = count($rows); 
if($totalrows){ ?>
    <tr>
    <?php  $i=1; foreach($totalrows as $r){ ?>
        <td>
            <?php echo $r['item'] . ": <input type=\"checkbox\" name=\"cart[]\"
              value=\"" . $r['item'] . "\">";?>
        </td>
        <?php if($i%2 == 0 && $totalrows != $i){ echo "</tr><tr>";  } ?>
    <?php $i++; } ?>
    </tr>
<?php } ?>
</table>