Page 1 of 1

HTML Table in a "while' loop

Posted: Mon Jan 03, 2005 12:35 pm
by raging radish
I've been staring at this all morning and it's just sitting there laughing at me.

The idea is to access a number of items from a database and show the results in a table, 3 columns wide. The problem is that I can't seem to get the <tr> and </tr> in the right spot to start/end a new table row. Here's what I have:

Code: Select all

print "<table cellpadding='2' cellspacing='2'>";
while (!$table_rows == "0"){
   print "<tr>";
      while ($display=mysql_fetch_array($result))  {
         $count = "3";
		if (!$count=="0") {
		   print "<td>";
		   print $display['filename'];
		   print "</td>";
		  $count--;
		}
          }
   $table_rows--;
   print "</tr>";
}
print "</table>";
Which results in the following HTML source:

Code: Select all

&lt;table cellpadding='2' cellspacing='2'&gt;&lt;tr&gt;&lt;td&gt;003.jpg&lt;/td&gt;&lt;td&gt;004.jpg&lt;/td&gt;&lt;td&gt;007.jpg&lt;/td&gt;
&lt;td&gt;008.jpg&lt;/td&gt;&lt;td&gt;009.jpg&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;/tr&gt;&lt;/table&gt;
I have a feeling I may be approaching this the wrong way.

Posted: Mon Jan 03, 2005 12:46 pm
by timvw
it's obvious that you don't have a clue what you are doing...

in that case you're best of _searching_ this forum, the web,.. because many others have had exactly the same problem. (and we answered that many times before too)

Posted: Mon Jan 03, 2005 1:09 pm
by feyd

Posted: Mon Jan 03, 2005 1:27 pm
by Trenchant
If you still can't get it I have wrote up a mini tutorial. I needed a change of pace right now anyway

Remember to follow the comments and understand the code. Dont just copy and paste it into your website. The goal you should have when coming here is to learn how to code.

Code: Select all

<?php
// First off you need to start the table.  Make sure you do this before any while loops
echo "<table border='1' cellpadding='2' cellspacing='2'>";

// Now we must declare variables used in the future parts of the script.
$maxcols = 3; // This is the most columns before a new line.
$count = 0; // This is how many entries are on the current line.

// Now get the information to put in a table using a while loop.
while($display = mysql_fetch_array($result)) {
// If this is a new line echo <tr>
   if($count == '0') {
      echo "<tr>";
   }
// Display the filename
   echo "<td>".$display[filename]."</td>";
// Add one to $count
   $count = $count + 1;

// if $maxcols have been met set $count = 0 and echo </tr>
   if($count == $maxcols) {
      $count = '0';
      echo "</tr>";
   }
}
// Now that the while loop is complete finish the table
echo "</table>";
// Remember that its also a good idea to CLOSE your mysql connections.
mysql_close();
?>

This is NOT tested but remember its a tutorial not a code snipit.