Forum Moderators: phranque

Message Too Old, No Replies

Diplaying data in certain order

         

toltec75

5:14 pm on Dec 29, 2004 (gmt 0)

10+ Year Member



This might be a n00bish question but is it possible for PHP to get data from database and display it in a way that there are 2 table cells filled with data from fetch_array() function and then a second row with 2 cells etc... With one fetch_array() function, of course. Maybe two.

1 2

3 4

5 6

rocknbil

4:29 pm on Dec 30, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The following is thought through with perl but can be applied with any looping mechanisms in php.

1. If ordination of the data other than the autoincrement id field is required, create a sequencing field in which you determine the data's sequence.

(Ascending is default)
"select data from table order by sequence_field"

2. Create a switch that determines start and end of table data rows.

$cols = 0; ## this is your switch.
$colcount = 2; ## This is the number of columns

print "<table">;
while (($data)=$sth->fetchrow_array) {
if ($cols == 0) { print "<tr>"; }
print "<td>$data</td>";
$cols++;
if ($cols > $colcount) {
print "</tr>";
$cols = 0; ## reset to 0. Next loop entry adds new <tr>
}
}

3. Create an error-free table close: If you've finished with an odd number (without closing </tr>) loop through to create empty cells. Although your example uses only two, this would fill out to $colcount columns.

if (($cols >0) && ($cols < $colcount)) {
for $i ($cols..$colcount) { print "<td>&nbsp;</td>"; }
print "</tr>";
}
print "</table>";

Of course there are other ways but this is one.