Forum Moderators: coopster

Message Too Old, No Replies

How to evenly list x items on 3 columns?

         

irock

4:04 am on Feb 14, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi I have a mysql database in which there are x rows. I would like to evenly list these items on 3 columns. Since I don't know how many items I'll have, is there some formulas on how to come up with the number of HTML rows required to display the items evenly?

Here's the structure of my HTML table...

<table>
<tr>
<td>x1 <br /> x2 <br /> x3 <br /> x4</td>
<td>x5 <br /> x6 <br /> x7 <br /> x8</td>
<td>blah blah blah</td>
</tr>
</table>

Any suggestions are welcomed.

coopster

3:29 pm on Feb 14, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You could change your design. Right now you are thinking in terms of columns and how many of each item am I going to have to put in each <td> of a three column layout. You could loop through and put each in a <td> of it's own:

$item_per_row = 3;
$content = '<tr>';
$sql = "SELECT * FROM table";
$rows = mysql_query($sql);
if (mysql_num_rows($rows) == 0) {
$content = '<td>No Items</td></tr>';
} else {
$count = 0;
while ($row = mysql_fetch_assoc($rows)) {
$content .= '<td>' . $row['item'] . '</td>';
if (++$count % $item_per_row === 0) $content .= '</tr>';
}
if ($count % $item_per_row !== 0) $content .= '</tr>';
}

irock

3:43 pm on Feb 14, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks for your help!

However, just wondering... if the number of items isn't divisible by 3, then there would be between 1 to 2 cells <td></td> not able to display, right?

In this case, how can we avoid a HTML rendering problem due to this?

coopster

3:51 pm on Feb 14, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



They would always be the last row of your table :)

You'll run into issues if you are applying style to your cells, that's when you'll have to modify the code a bit.