Forum Moderators: coopster

Message Too Old, No Replies

Formatting sql query results into 3 columns

reading DOWN, not across

         

FairyV

2:32 pm on Oct 4, 2005 (gmt 0)

10+ Year Member



Greetings,

I would like to know how to arrange a list of sql query results into a 3-column (i.e. 3-cell) table, such that they read alphabetically going down column 1, then column2, etc.

So far I have only found advice for arranging values across table columns.

Any help will be gratefully appreciated.

Here's the code I'm currently using (single-cell table):

echo '<table class="catlist"><tr><td>';
while ($row = mysql_fetch_array($result)) {
echo '<a href="list.php?no=',$row['id'],'">',$row['category'],'</a> <font size="-1">[Fics: x]</font><br>';
}
echo '</td></tr></table>';

~FairyV

killroy

3:02 pm on Oct 4, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Do you want to display one line of table for each result row (which is easy)? Or do you want to show results 1-10 in column one and 11-20 in column 2 and 21-30 in column 3? This is more complex but not hard to do either. Let us know and we'll post a quick solution ;)

FairyV

5:45 pm on Oct 4, 2005 (gmt 0)

10+ Year Member



The latter, but obviously for an ever-expanding list!

With thanks, FairyV

arran

11:19 pm on Oct 4, 2005 (gmt 0)

10+ Year Member



Hi FairyV,

Try something like:


$rows_returned = mysql_num_rows($result);
$base = $rows_returned/3;
$first_column = $second_column = $third_column = $base;
if ($base % 3 > 0) {
$first_column++;
}
if ($base % 3 > 1) {
$second_column++;
}
$first_break = $first_column;
$second_break = $first_column + $second_column;
echo '<table class="catlist"><tr><td>';
for ($i = 1; $i <= $rows_returned; $i++) {
$row = mysql_fetch_row ($result);
echo '<a href="list.php?no=',$row['id'],'">',$row['category'],'</a><font size="-1">[Fics: x]</font><br>';
if ($i == $first_break ¦¦ $i == $second_break) {
echo '</td></td>';
}
}
echo '</td></tr></table>';

arran.

FairyV

11:38 am on Oct 5, 2005 (gmt 0)

10+ Year Member



Dear arran,

Thank you for that script. However, I am getting a parse error for the line:

if ($i == $first_break ¦¦ $i == $second_break) {

Since I don't fully understand what it means I cannot correct it.

I also wondered whether the following line:

echo '</td></td>';

should read:

echo '</td></tr>';

With thanks, FairyV

arran

12:36 pm on Oct 5, 2005 (gmt 0)

10+ Year Member



I forgot webmasterworld formatting breaks vertical bars. Change the ¦¦ to 2 proper vertical bars (shift + \).

You are correct about the other change - my typo.

FairyV

3:13 pm on Oct 5, 2005 (gmt 0)

10+ Year Member



Thanks, arran. With those changes (and mysql_fetch_array, since I'm using text labels) there are no sql errors but the results are still only in one column!