从数据库中收集表的列名

时间:2015-10-20 22:03:18

标签: php mysql database

获取数据库表的列名并在php页面中显示它们的最佳方法是什么?我只能收集并显示表格行。

$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('...');
$query = "SELECT * FROM ...";

$result = mysql_query($query);

echo "<table class='table'>";
echo '<tr>';
for ($i = 0; $i < mysql_num_fields($result); $i++) { 
    echo "<th>".mysql_field_name($result, $i)."</th>"; 
}
echo '</tr>';
while($row = mysql_fetch_array($result)){  
echo "<tr class='info'><td>" . $row['name'] . "</td>
               <td>" . $row['mail'] . "</td>
               <td>" . $row['number'] . "</td>
               <td>" . $row['price'] . "</td>
               <td>" . $row['paymenttype'] . "</td>
               <td>" . $row['pcname'] . "</td>
               </tr>";  
}
echo "</table>"; 
mysql_close(); 
?> 

2 个答案:

答案 0 :(得分:-2)

使用

执行单独的查询
SHOW COLUMNS FROM {table_name}

答案 1 :(得分:-2)

http://php.net/manual/en/function.mysql-num-fields.php

$result = mysql_query("select * from table"); 

echo '<tr>';
for ($i = 0; $i < mysql_num_fields($result); $i++) { 
    echo "<th>".mysql_field_name($result, $i)."</th>"; 
}
echo '</tr>';