Reputation: 327
How can I make a select
in database and display that row in a table with 2 columns.
Here is my select
$query="select Interval from Interval_Orar";
$result=mysqli_query($dbc,$query) or die("query failed: " . mysqli_error($dbc));
echo '<table>';
while ($row=mysqli_fetch_array($result))
{
echo'
<tr>
<td>'.$row['Interval'].'</td>
</tr>';
}
echo '</table>';
what i what to display is a table like this
<tr>
<td>Interval 1</td>
<td>Interval 2</td>
</tr>
<tr>
<td>Interval 3</td>
<td>Interval 4</td>
</tr>
<tr>
<td>Interval 5</td>
<td>Interval 6</td>
</tr>
what i dont know to make is to put that 2 by 2 select in the while
Upvotes: 0
Views: 72
Reputation: 40842
You could just do another mysqli_fetch_array
in the loop, check if there was a result
and display either an empty cell or one with the content.
Then at the end of the loop you only need to check if the second mysqli_fetch_array
had a result. (The empty cell is optional, it depends if you require it e.g. for styling, add not value
or other things)
while ($row=mysqli_fetch_array($result))
{
echo'<tr>';
echo '<td>'.$row['Interval'].'</td>';
$row=mysqli_fetch_array($result);
if( $row ) {
echo '<td>'.$row['Interval'].'</td>';
} else {
echo '<td></td>';
}
echo '</tr>';
if( !$row ) {
break;
}
}
Another way would be to use a $counter
and a $counter%2
to check in which column the result should be displayed and if an <tr>
or </tr>
needs to be added, but that would require more work.
EDIT
This is not tested as I neither have php
not a mysql
setup server right here, but making a function out of it would allow you to re use it with any column count:
function createRows( $result, $columns ) {
if( $columns <= 0 ) {
return;
}
$row = true; //initialize it with true so that the first mysqli_fetch_array will be called
while($row !== null ) {
echo'<tr>';
for( $i=0 ; $i<columns ; $i++ ) {
if( $row !== null && $row=mysqli_fetch_array($result) ) {
echo '<td>'.$row['Interval'].'</td>';
} else {
echo '<td></td>';
}
}
echo '</tr>';
}
}
Upvotes: 2
Reputation: 4659
Dump your entire result set into an array so you can manually move the pointer. The inside your loop it would be (in plain English)
column1 = row1 column2 = row1+1
row = row + 1
repeat.
Upvotes: 0