How can I echo all columns of my table without having to spe

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
aneuryzma
Forum Contributor
Posts: 106
Joined: Sat May 17, 2008 7:03 am

How can I echo all columns of my table without having to spe

Post by aneuryzma »

How can I echo all columns of my table without having to specify the headers ?

Code: Select all

while ($row = mysql_fetch_assoc($result)) {
			
	echo $row['FirstColumn'];  //NO
	echo $row['SecondColumn']; //NO
...

}
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: How can I echo all columns of my table without having to

Post by Eric! »

Here's a quick way to explore a random sql database and dump it to an html table.

Code: Select all

$sql = "SELECT * FROM `myTable`";
$result = mysql_query($sql);
$output='<table border="1">';
while ($row = mysql_fetch_row($result))
{
 $output.='<tr>';
 for($j=0;$j<mysql_num_fields($result);$j++)
	 {
		  $output.="<td>".$row[$j]."</td>";
	 }
	 $output.="</tr>"; 
}
$output.='</table>';
echo $output;
You can also use the mysql_fetch_assoc and then foreach if you want to show the key and value like in this example from the php.net manual:

Code: Select all

function array2table($arr,$width)
   {
   $count = count($arr);
   if($count > 0){
       reset($arr);
       $num = count(current($arr));
       echo "<table align=\"center\" border=\"1\"cellpadding=\"5\" cellspacing=\"0\" width=\"$width\">\n";
       echo "<tr>\n";
       foreach(current($arr) as $key => $value){
           echo "<th>";
           echo $key."&nbsp;";
           echo "</th>\n";  
           }  
       echo "</tr>\n";
       while ($curr_row = current($arr)) {
           echo "<tr>\n";
           $col = 1;
           while (false !== ($curr_field = current($curr_row))) {
               echo "<td>";
               echo $curr_field."&nbsp;";
               echo "</td>\n";
               next($curr_row);
               $col++;
               }
           while($col <= $num){
               echo "<td>&nbsp;</td>\n";
               $col++;      
           }
           echo "</tr>\n";
           next($arr);
           }
       echo "</table>\n";
       }
   }
$query = "SELECT * FROM mytable";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
  $array[] = $row; }
     
array2table($array,600); // Will output a table of 600px width
Post Reply