Wednesday, April 1, 2009

MySql Table to HTML Table

Hi to all!!

happy april :p like CADIE?

Well now i want to exctract a little preview form dbi that should be useful to someone.

This is a php function and could needed to be a little change from you. in_table function print out a HTML table showing the results of a SELECT query. Actually the function (as it is) need an existent mysql connection and the function mysql_select_db() already called. Then you could add classes to HTML Table element to style as you want.

All the game is based on mysql_fetch_assoc() and array_keys(). It first execute the query (without security check =P) then while cycle result with mysql_fetch_assoc(); then check an internal counter with a value as modulus to "decide" if print headers again or not (headers is the field name or their aliases).
Here the function:

function in_table($query, $repeat = 50) {
$result = mysql_query($query);
if(!$result) {
echo "Error: ".mysql_error();
die();
}
$counter = 0;
echo "<table>";
while($data = mysql_fetch_assoc($result)) {
echo "<tr>";
if($counter % $repeat == 0) {
$fields = array_keys($data);
foreach($fields as $field)
echo "<th>$field</th>";
echo "</tr><tr>";
$counter = 0;
}
foreach($data as $val)
echo "<td>$val</td>";
echo "</tr>";
$counter++;
}
echo "</table>";
}


Here a little snapshoot about the output ^^