PHP Function to Generate HTML Table Using MySQL Database Data

Organize your MySQL database data in HTML tables created on the fly using this PHP function snippet. Function maketable uses MySQL query and an array of  columns you want to display as attributes.

Function

function maketable($query, $fieldarray){
//count number of columns
 $columns = count($fieldarray);
//run the query
 $result = mysql_query($query) or die(mysql_error()) ;
 $itemnum = mysql_num_rows($result);
 if($itemnum > 0){ 
  do{   
   echo "< tr >" ;
   for($x = 0; $x < $columns; $x++){
    echo "< td >" .$items[$fieldarray[$x]]. "< /td >" ;
   }
   echo "< /tr >" ;
  }while($items = mysql_fetch_assoc($result));
 }
}

Usage

echo "< table >";
$fieldarray = array("id","title","description");
maketable("SELECT * FROM bw_news", $fieldarray);
echo "< /table >";

 

    Comments

    April 28th 2010

    Serdar - Thanks for the useful function. Line 6 in the function supposed to be like this $itemnum = mysql_num_rows($result);

    Emir - Fixed. Thanks for catching this.

    Reply

    Add Comment | Contact me