Printing DB fields to table columns

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Czar
Forum Commoner
Posts: 58
Joined: Sun Dec 29, 2002 11:17 am

Printing DB fields to table columns

Post by Czar »

How can i simplify this? I want to print contents of a rows from MySQL into a table so, that each value of a field prints to a table cell horizontally and when next row starts from db it prints to next table row. How can i do it so, that i dont need to specify a number of columns, but column number is automatically a number of fields in a row?

Here's the code

Code: Select all

<?php
$field_list = mysql_query("SELECT * FROM $table") or die(mysql_error());
	if(mysql_num_rows($field_list)) {
	  print "<table border=1 cellspacing=0>\n";
	   while($field = mysql_fetch_array($field_list)) {
		  print "<tr><td>".$field['0']."</td><td>".$field['1']."</td><td>".$field['2']."</td>
			<td>".$field['3']."</td><td>".$field['4']."</td><td>".$field['5']."</td>
			<td>".$field['6']."</td><td>".$field['7']."</td><td>".$field['8']."</td>
			<td>".$field['9']."</td><td>".$field['10']."</td></tr>";
			}
		print "</table>";
?>
I would appreciate any help.
?>
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Post by liljester »

Code: Select all

<?php
$field_list = mysql_query("SELECT * FROM $table") or die(mysql_error());

if(mysql_num_rows($field_list))
{
     print"<TABLE border="1" cellspacing="0">\n";
     $num_fields = mysql_num_fields($field_list);
     while($field = mysql_fetch_array($field_list))
     {
          print"<TR>\n";
          $current_field = 0;
          while($current_field < $num_fields)
          {
               print"<TD>$field[$current_field]</TD>\n";
               $current_field++;
          }
          print"</TR>\n";
     }
     print"</TABLE>\n";
}

?>
Czar
Forum Commoner
Posts: 58
Joined: Sun Dec 29, 2002 11:17 am

Post by Czar »

Thanks. Cleared it.
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Post by liljester »

Sweet =)
Post Reply