I am trying to put queried info from a mysql database into a table. I'd like the table to apear as 4 across and 4 down. how would i interupt the table to end one row and start another? like <table> while(whatever){ code here... and every 4 iteration start a new row} </table> Any ideas? i'll get the code up in one sec.
$result = mysql_query("select photo from photo where email='".$valid_user."' "); ?> <table border="1" > <?php while($row = mysql_fetch_row($result)) {?> <tr><td> <img src= "images/<?php echo $row[0]; ?>" alt="<?php echo $row[0]; ?>" /> </td></tr><?php }?> </table><?php }?> <?php
I would do it like this think its about right. didnt test it $result = mysql_query("select photo from photo where email='".$valid_user."' "); ?> <table border="1" > <?php $counter = 1; while($row = mysql_fetch_row($result)) { if ($counter==1) { echo '<tr>'; } echo '<td> <img src= "images/'.$row[0].'" alt="'.$row[0].'" /> </td>'; $counter++; if ($counter==4) { echo '</tr>'; $counter=1; } } if ($counter !=1) { for ($counter; $counter<=4; $counter++) { echo '<td> </td>'; } ?> </table> Code (markup):
<?php $i = 0; $num = 4; $rows = 4; echo "<table>\n<tr>"; while ($i++ < 10){ echo "<td>data here</td>\n"; if ($i == $num) { $num = ($num+$rows); echo "</tr><tr>\n"; } } echo "</tr></table>"; ?> PHP:
Only problem with your code is that if the last row only has 2 data cells the table might not be displaying nicely as the last 2 cells would be missing.
You need to use the modulus operator "%" - http://php.net/manual/en/internals2.opcodes.mod.php Something like this: <?php $query = "SOME QUERY RESULT..."; $rows = mysql_num_rows($query); $number_of_columns = 4; //Change this to create more of less columns $count = 1; ?> <table> <?php while($result = mysql_fetch_array($query)) { if($count == 1 || $count%$number_of_columns==1) { echo '<tr>'; } echo '<td>'.result['some_column'].'</td>'; if($count == $rows || $count%$number_of_columns==0) { echo '</tr>'; } $count++; } ?> </table> PHP: Control the number of results selected in your mysql statement and not on your application. This way you only receive the data you want. Use LIMIT or other functions to control the result set.
thanks for the help folks. i ended up blending your two answers and came up with this. It limits the number of rows to 16 photos per page in the mysql and the rest was your ideas. if anyone else needs it it is. $counter = 1; $i=0; while($row = mysql_fetch_row($result)) { if ($counter==1) { echo '<tr>'; } print "<td> </td>"; $counter++; $i++; if ($counter==5) { echo '</tr>'; $counter=1; } $count++ ; } works great ty