Php 从数据库结果中获取字段名
这里我想从存储在变量$table中的表名中获取字段名。并希望生成字段名称的表标题。我尝试过的这种方法有什么问题:Php 从数据库结果中获取字段名,php,mysql,Php,Mysql,这里我想从存储在变量$table中的表名中获取字段名。并希望生成字段名称的表标题。我尝试过的这种方法有什么问题: <?php $sql=mysql_query("show fields from $table"); if(mysql_num_rows($sql)) while($res = mysql_fetch_object($sql)) { ?> <th><?php echo $res->fie
<?php
$sql=mysql_query("show fields from $table");
if(mysql_num_rows($sql))
while($res = mysql_fetch_object($sql))
{
?>
<th><?php echo $res->field; ?></th>
<?
}
else
{
echo "No data to display";
}
?>
查询必须是
$sql=mysql_query("show columns from $table");
$printTHs=true;
而($res=mysql\u fetch\u assoc($sql))
{
如果($printTHs)
{
printTableHeader($res);
$printTHs=false;
}
回声“;
foreach($res作为$val)
{
回声“$val.”;
}
回声“;
}
函数printTableHeader($res)
{
回声“;
foreach($res作为$col=>$val)
{
回声“$col.”;
}
回声“;
}
使用mysql\u fetch\u assoc()
然后使用array\u keys()
获取密钥。这将返回一个包含所有键的数组
使用
foreach()
$results = mysql_query('SELECT * FROM ' . $table);
if (mysql_num_rows($results))
{
echo '<table>';
$first = TRUE;
while ($row = mysql_fetch_assoc($results))
{
if ($first = TRUE)
{
echo '<tr>';
foreach ($row as $k => $v)
echo '<th>' . $k . '</th>';
echo '</tr>';
$first = FALSE;
}
echo '<tr>';
foreach ($row as $column)
echo '<td>' . $column . '</td>';
echo '</tr>';
}
echo '</table>';
}
$results=mysql\u查询('SELECT*FROM'.$table);
if(mysql_num_行($results))
{
回声';
$first=TRUE;
while($row=mysql\u fetch\u assoc($results))
{
如果($first=TRUE)
{
回声';
foreach($k=>v的行)
回音“.$k.”;
回声';
$first=FALSE;
}
回声';
foreach($行作为$列)
回显“.$column.”;
回声';
}
回声';
}
我现在已更改..但获取时仍然没有结果:(是否要显示表结构或表的数据?如果两者都要,请查看CodeMaster的答案!我只想将数据库表的列名显示为html表的标题删除If
和else
并重试。在If
更改$res->field;为$res之后缺少括号->fields;@JapanPro,nofield
是正确的:请修复您的问题标题。它根本没有描述问题。为什么您认为有问题?运行此代码时会发生什么?您执行了什么调试?顺便说一句,调用mysql\u查询的结果(…)
$sql
有误导性。您向mysql\u query
提供的查询是一条sql语句;从中返回的结果是一个数据库记录资源,与sql无关。这将跳过结果的第一行。
$results = mysql_query('SELECT * FROM ' . $table);
if (mysql_num_rows($results))
{
echo '<table>';
$first = TRUE;
while ($row = mysql_fetch_assoc($results))
{
if ($first = TRUE)
{
echo '<tr>';
foreach ($row as $k => $v)
echo '<th>' . $k . '</th>';
echo '</tr>';
$first = FALSE;
}
echo '<tr>';
foreach ($row as $column)
echo '<td>' . $column . '</td>';
echo '</tr>';
}
echo '</table>';
}