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 >";

Fabio Souto
For better performance I would do (inside the function):
$sql_fields = implode(“,”,$fieldarray);
$query = str_ireplace(“SELECT *”, “SELECT $sql_fields”,$query);
ramesh
good one, realy hepfull for beginers like me
Simon
I dont know how this work since i dont see how to make db conectio i try this example without success
Jessica_Y
Very useful code.
Thanks a lot.
It generate table with sql data correctly.
But i got this warning .
Notice: Undefined variable:
I don’t know why