如何使用PHP显示表的列名?

时间:2012-11-18 14:40:49

标签: php mysql

我已经研究了好几天了。我总是得到这样的东西(这是我认为最好的答案):

SELECT `COLUMN_NAME` 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='yourdatabasename' 
AND `TABLE_NAME`='yourtablename';

是的,这个在SQL中完美运行,但我仍然不知道如何创建一个PHP脚本来显示它与在SQL中一样。谁能给我一个代码?

我现在真的很困惑。请帮忙..

3 个答案:

答案 0 :(得分:2)

没有PDO:

$sql = "SHOW FIELDS FROM users;";
$result_sql = mysql_query($sql) or die ("Error!\n");

    while ($row = mysql_fetch_array($result_sql)) {
        echo $row['Field']."<br>\n";
    }

答案 1 :(得分:1)

您可以在mysql mysql_field_name()

中执行此操作

不鼓励使用mysql_*,因此请使用pdomysqli

与他们一起你可以通过

来做到这一点
mysqli_fetch_field_direct()   //for mysqli
PDOStatement::getColumnMeta() //for pdo

例如在OP comment

之后
$sql = "SELECT * from Person";
$result = mysql_query($sql,$con);

$name = mysql_field_name($result, 0);

解释如何使用mysql_field_name()

<强>了Syntex

mysql_field_name(data,fieldOffset) 

+------------+------------------------------------------------------------------+
| data       | Required. Specifies which data pointer to use. The data          |
|            | pointer is the result from the mysql_query() function            |
+------------+------------------------------------------------------------------+
|fieldOffset |Required. Specifies which field to start returning. 0 indicates   |
|            |the first field                                                   |
+------------+------------------------------------------------------------------+

好读

PDO Tutorial for MySQL Developers

答案 2 :(得分:1)

显然你需要从mysql表中检索数据,然后用php做一些事情。有几种方法可以做到这一点,这是我的最爱:

<?php
    $query="SELECT `COLUMN_NAME` 
            FROM `INFORMATION_SCHEMA`.`COLUMNS` 
            WHERE `TABLE_SCHEMA`='yourdatabasename' 
            AND `TABLE_NAME`='yourtablename'";
    $result=mysql_query($query); //This will store the whole result table in $result
    $rows=array(); //Initialize array
    while($row=mysql_fetch_object($result)) $rows[]=(object) $row; //Store each row of the result table in the array $rows

    //Now you can access, for example, the third row and second column by saying:
    echo $rows[2]->name_of_second_column
?>

另请参阅this tutorial.,了解如何从数据库中检索数据并在之后对其进行操作。