Overlib, iframe, other sites | Home | Thumbs+ & SQL Server 2005 Express

June 7, 2006

PEAR DB tableinfo();

I needed a quick function in PHP that would generate HTML tables from database information. The issue was that the column names would not be known in advance for some of the more generic queries so I found the solution using the PEAR DB tableinfo() function. This function does exactly what I needed - it "gets info about columns in a table or a query result". Perfect. So I created a function that takes a valid query for your database and formats the results into a nice HTML table, which I find useful for reporting pages (easily imported into Excel or Calc).

Here is the code:


// ***********************************************************************
// ** Begin Loopthru - a generic query/output display function
// ***********************************************************************
function loopThru($sqlQuery)
{
global $sqlConnection;

$getResults = $sqlConnection->query($sqlQuery);
if (DB::isError($getResults))
die ($getResults->getMessage());

$rowcount = $getResults->numRows();
$tableinfo = $getResults->tableInfo(DB_TABLEINFO_ORDER);
$num_fields = $tableinfo["num_fields"] ;

if ($rowcount > 0) {

echo "<!-- DATA TABLE -->\n\n";
echo "<table border=1>\n";

echo "<tr>\n";
for ($i = 0; $i < $num_fields; $i++) {
echo "<td nowrap>" . $tableinfo[$i]["name"] . "</td>\n";
}
echo "</tr>\n";
while ($row = $getResults->fetchRow()) {
echo "<tr>\n";
for ($i = 0; $i < $num_fields; $i++) {
echo "<td>" . $row[$i] . "</td>\n";
}
echo "</tr>\n";
}

echo "</table>\n\n";
echo "<!-- END DATA TABLE -->\n\n";

}
}



Comments are closed.