Page 1 of 1

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

Posted: Wed Sep 07, 2011 8:50 am
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
...

}

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

Posted: Wed Sep 07, 2011 9:20 am
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