Mick White wrote:
IS it possible in PHP to grab the headers following a mySQL query?
SELECT [headings] from tablename.
I'm looking for a generic PHP function that will include the headings,
so that I can display a meaningful table.
If you use mysql_fetch_assoc() or mysql_fetch_array() with MYSQL_ASSOC
as the 2nd parameter then you'll get an array indexed with the column
names.
For example:
$res = mysql_query('select a, b, c from foo');
$row = mysql_fetch_assoc($res);
print '<table><tr>';
foreach($row as $name => $value) {
print "<th>$name</th>";
}
print '</tr>';
while($row) {
print '<tr>';
foreach($row as $value) {
print "<td>$value</td>";
}
print '</tr>';
$row = mysql_fetch_assoc($res);
}
print '</table>';
http://www.php.net/mysql_fetch_assoc http://www.php.net/mysql_fetch_array
You can also use the mysql_fetch_field() and mysql_field_name()
functions.
for($i = 0; $i < mysql_num_fields($res); $i++) {
print '<th>' . mysql_field_name($res, $i) . '</th>';
}
http://www.php.net/mysql_fetch_field http://www.php.net/mysql_field_name http://www.php.net/mysql_num_fields(
--
Chris Hope - The Electric Toolbox -
http://www.electrictoolbox.com/