简体   繁体   English

如何从给定的 MySQL 表中获取列名?

[英]How do I get column names from a given MySQL table?

How do I get the column names of a table into a PHP array using the mysqli extension?如何使用 mysqli 扩展将表的列名放入 PHP 数组? I need to fetch the column names of any given table without fetching any data from the table.我需要获取任何给定表的列名,而不需要从表中获取任何数据。

The following code gets all column names from table table_name :以下代码从表table_name获取所有列名:

$mysqli = new mysqli('localhost', 'USERNAME_HERE', 'PASSWORD_HERE', 'DATABASE_HERE');

$sql = 'SHOW COLUMNS FROM table_name';
$res = $mysqli->query($sql);

while($row = $res->fetch_assoc()){
    $columns[] = $row['Field'];
}

Since I have the columns id and name in my table, this is the result:由于我的表中有列idname ,因此结果如下:

Array
(
    [0] => id
    [1] => name
)

If you want to get the columns from a resultset, it depends, but here is one way to do it:如果您想从结果集中获取列,这取决于,但这是一种方法:

$mysqli = new mysqli('localhost', 'USERNAME_HERE', 'PASSWORD_HERE', 'DATABASE_HERE');

$sql = 'SELECT * FROM table_name';
$res = $mysqli->query($sql);

$values = $res->fetch_all(MYSQLI_ASSOC);
$columns = array();

if(!empty($values)){
    $columns = array_keys($values[0]);
}

Example result for $columns : $columns示例结果:

Array
(
    [0] => id
    [1] => name
)

Example result for $values : $values示例结果:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Name 1
        )

    [1] => Array
        (
            [id] => 2
            [name] => Name 2
        )

)

You can use array_keys() to get all the keys of an array,您可以使用 array_keys() 获取数组的所有键,

$myarray = array('key1' => 'a', 'key2' => 'b')
$x = array_keys($myarray);

The result you want can be obtained from $x你想要的结果可以从 $x 中得到

$x = array(0 => 'key1', 1 => 'key2');

Inorder to get the column names of a table,为了获取表的列名,

$sql = "SELECT * FROM table_name LIMIT 1";
$ref = $result->query($sql);
$row = mysqli_fetch_assoc($ref);
$x = array_keys($row);

now $x array contains the column names of the table现在 $x 数组包含表的列名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM