Forum Moderators: coopster

Message Too Old, No Replies

Looping problem with whiles and ifs

a table with 3 td's in each row

         

Trisha

7:31 pm on Mar 2, 2004 (gmt 0)

10+ Year Member



I'm trying to display records in a table, with 3 td's across before another tr begins. I've gotten as far as the code below. But this doesn't really work right, and I understand why - the same item gets repeated three times, in the same table row. I can't figure out how to fix it though.


while ($subcategory=mysql_fetch_array($subcategory_result)){
echo "<tr>";
for ($i=1; $i<=3; $i++){
echo "<td>html stuff here </td>";
}
echo "</tr>";
}

I tried putting the while within the 'for', but the table row also needs to be looped through so this won't work either.

I really appreciate the patience of the regulars here who help out people like me. I'm actually enjoying doing PHP/MySQL work, but I just don't seem to be very good at it!

And as pathetic as this sounds - I'm actually quite proud of myself for having figured out how to do the counter to create 3 table datas before another table row starts! I just can't get the data into it right now.

jatar_k

7:48 pm on Mar 2, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



what about using a control structure to have it know which cell it is to output?

$cell = 1; 
while ($subcategory=mysql_fetch_array($subcategory_result)){
if ($cell == 1) echo "<tr>";
echo "<td>html stuff here </td>";
if ($cell == 1) {
$cell = 2;
} else if ($cell == 2) {
$cell = 3;
} else {
$cell = 1;
echo "</tr>";
}
}
//at this point we need to make sure the table is closed properly
if ($cell == 2) {
echo "<td>&nbsp;</td></tr>";
} else if ($cell == 3) {
echo "<td>&nbsp;</td>";
echo "<td>&nbsp;</td></tr>";
}
echo "</table>";

Trisha

8:44 pm on Mar 2, 2004 (gmt 0)

10+ Year Member



Thanks jatar_k - that worked! It took me a long time to understand how/why it works, but I think I get it now. I thought there would have been an easier way to do it though. I never would have been able to come up with something like this myself either!

jatar_k

9:17 pm on Mar 2, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



most of it is to make sure the table gets closed properly. It needs to know how many more cells to output and whether or not to close the row.

I have one lying around somewhere that has a lot tighter code but I figured I would use the verbose one as it is easier to understand the steps.

glad it helped