i have this code:
<table id="table" style="width: 100%; text-align: center;" border="0">
<?php while ($row = $q->fetch()): ?>
<tr>
<th></th>
<th></th>
</tr>
<tr>
<td id="columna1">
<div >
<div >
<br>
<br>
<div >
<img src="assets/images/foodmenu/<?php echo $row['imagen']?>" href="#foodmenu1">
</div>
<div >
<h3 ><?php echo $row['product_name']?></h3>
<p><?php echo $row['descripcion']?></p>
<div ><span>$</span><?php echo $row['price']?></div>
<div >
<a href="#" >Add to cart</a>
</div>
</div>
</div>
</div>
</td>
<td id="columna2">
</td>
</tr>
<?php endwhile; ?>
</table>
as you can see, the "columna2" td, is empty cause i want to populate each database row on each to get the population in 2 columns and i don't know how to make it. it's something like this:
1 2
3 4
5 6
I try to do it on diferent ways but have no luck! Please if yo need more details please let me know i am new.
Thank you all
CodePudding user response:
I'm not sure I understand what exactly you mean. If you want a table with 2 columns I would do it that way
Add "num" variable like this:
<?$num = 1;?>
<table id="table" style="width: 100%; text-align: center;" border="0">
<?php while ($row = $q->fetch()): ?>
<?if ($num==1){?><tr>
<th></th>
<th></th>
</tr>
<tr>
<?}?>
<td id="columna<?echo $num?>">
<div >
<div >
<br>
<br>
<div >
<img src="assets/images/foodmenu/<?php echo $row['imagen']?>" href="#foodmenu1">
</div>
<div >
<h3 ><?php echo $row['product_name']?></h3>
<p><?php echo $row['descripcion']?></p>
<div ><span>$</span><?php echo $row['price']?></div>
<div >
<a href="#" >Add to cart</a>
</div>
</div>
</div>
</div>
</td>
<?if ($num==2){?></tr><?}>
<?if ($num==1) $num=2; else $num=1?>
CodePudding user response:
Start by putting all of the results in an array first.
$num = mysqli_num_rows($query);
$result_array = [];
for($i = 1; $i <= $num; $i ) {
$result = mysqli_fetch_array($query);
$result_array[] = $result;
}
And start to construct a table using a loop.
<table>
<thead>
<tr>
<th>| Column 1 |</th>
<th>| Column 2 |</th>
</tr>
</thead>
<tbody>
<?php
$column_size = 2;
for($row = 0; $row < $num / $column_size; $row ) {
echo '<tr>';
for($column = 0; $column < $column_size; $column ) {
echo '<td>';
echo 'ID: '.$result_array[($row * $column_size) $column]['u_id'];
echo '</td>';
}
echo '</tr>';
}
?>
</tbody>
</table>
The result: https://i.stack.imgur.com/CQSny.png