1

我创建了一个 mysql 查询并将结果显示在表中,但想将 mysql 表中的字段或列名作为表头。我想对多个 php 文件执行此操作,但其中一个有点复杂,因为它使用 for 循环来显示由公共字段相互关联的记录。这是简单的结果表

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

我不知道在哪里,但标签以及如何获取 mysql 列名。我用 mysql_field_names 尝试了一些东西,但没有运气。这是另一个带有 for 循环的表。

$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>";
}
4

2 回答 2

2

将第一行作为关联数组提取后,您可以使用array_keys($line).

如果您决定停止使用已弃用的 ext/mysql 函数,并切换到 ext/mysqli 或 pdo_mysql,您可以享受mysqli_stmt::result_metadata()PDOStatement::getColumnMeta()等不错的函数。

于 2012-12-08T23:47:21.450 回答
0

尝试在<th>循环上方添加一个foreach ($line as $col_name => $col_value)循环

$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

此外,在代码的第 7 行,您的表格元素无效 -

  echo "<td><tr align='center'>\n";
于 2012-12-08T23:46:33.523 回答