php mysql字段名称为?

时间:2012-12-08 23:29:59

标签: php mysql

我创建了一个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>";
}

2 个答案:

答案 0 :(得分:2)

将第一行作为关联数组提取后,可以使用array_keys($line)获取列名。

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

答案 1 :(得分: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";