How to display data in multiple columns with php?
Hi I need to build a table with two columns from a mySQL table.
Here is what i have now:<table>
<?php
$sql = "SELECT field1, field2 FROM tblX"
$result = mysql_query($sql) or die("\nError Retrieving Records.");
while($row = mysql_fetch_array ($result, MYSQL_ASSOC)){?>
<tr>
<td>
<?=$row['field1']?> - <?=$row['field2']?>
</td>
</tr>
<?php }?>
</table>
This will create one col开发者_JS百科umn table like so:
1
2
3
4
5
I need the table to be in two columns like this:
1 4
2 5
3
Is this possible if it is how do I do that?
This should do what you want, if you insist on a table.
Get the mid point:
$mid = ceil(mysql_num_rows($result)/2);
Get an array:
while( $row = mysql_fetch_row($result) ) {
$list[] = $row; }
Output the rows:
for( $i = 0; $i < $mid; $i++ ) {
$itemOne = $list[$i];
$itemTwo = $list[$i + $mid];
// echo them in two tds.
}
I agree with marco, though. You could just as easily list items one to $mid in one div, then $mid to the end in another, and use CSS to float the divs side-by-side. Using tables for formatting purposes is evil.
read all values in a list, get the half value, write a loop that shows [i] and [i+halfvalue] together
Your question is unclear, but it sounds like you want to rearrange how the data is displayed and don't want the standard row-by-row output. You should probably do this manually if your order requires a method that cannot be looped through.
You should arrange the table BEFORE you output it, then once you've got everything all tidy, simply output the code.
Must it be in tables? If you have in it a div and you have it set so that 3 items can contain in the height.
<div id="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
</div>
#container { height: 300px; }
.item { height: 100px; }
You can use some css floating to solve that combined with some padding and margin.
精彩评论