Reputation: 17
I have created a mysql query and have the results displaying in a table but would like to put the field or column names from the mysql table as the table headers. I would like to do this with multiple php files but one is a little complicated because it uses a for loop to display records tied to each other by a common field. Here is the easy result table
echo "<table border='1' width='85%' cellpadding='5' align='center'>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr align='center'>\n";
foreach ($line as $col_value) {
echo "\t\t<td align='center'>$col_value</td>\n";
}
echo "<td align='center'><img src=./images/$col_value border='3' ></td>";
echo "\t</tr>\n";
}
echo "</table>\n";
I'm not sure where to but the tag and how to get the mysql column names. I tried something with mysql_field_names and no luck. Here is the other table with the for loop.
$last_pattern = null;
echo "<table border='1' width='80%' cellpadding='5' align='center'>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
$col_count = count($line) - 1; // Subtract 1 because image isn't in a column
if ($line['PatternName'] !== $last_pattern) {
if ($last_pattern !== null) {
echo "<td><tr align='center'>\n";
}
echo "<tr align='center'>\n ";
foreach ($line as $col_name => $col_value) {
switch ($col_name) {
case 'YarnImage':
break;
case 'PatternImage':
echo "<td><image src='images/$col_value' /></td>";
break;
default:
echo "<td>$col_value</td>";
}
}
$last_pattern = $line['PatternName'];
echo "</tr>\n <tr align='center'><td colspan='$col_count'>\n";
}
$yarn_image = $line['YarnImage'];
echo "<img src='images/$yarn_image' width='150' height='150' border='3'/>\n";
}
if ($last_image !== null) {
echo "</td></tr>";
}
Upvotes: 1
Views: 351
Reputation: 12433
Try adding a <th>
loop above you foreach ($line as $col_name => $col_value)
loop
$col_number = 1; // add a counter
foreach ($line as $col_names => $col_values) {
if ($col_number <= $col_count){ // check if counter is >= to $col_count
echo "<th>$col_names</th>";}
$col_number++;} // increase counter by 1
foreach ($line as $col_name => $col_value) {
... //rest of you code
Also, on the 7th line of your code, you have an invalid table element -
echo "<td><tr align='center'>\n";
Upvotes: 0
Reputation: 562398
After you have fetched the first row as an associative array, you can get the column names with array_keys($line)
.
If you decide to stop using the deprecated ext/mysql functions, and switch to ext/mysqli or pdo_mysql, you can enjoy nice functions like mysqli_stmt::result_metadata() or PDOStatement::getColumnMeta().
Upvotes: 2