如何从给定的 MySQL 表中获取列名? [英] How do I get column names from a given MySQL table?

查看:68
本文介绍了如何从给定的 MySQL 表中获取列名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 mysqli 扩展将表的列名放入 PHP 数组?我需要获取任何给定表的列名,而不需要从表中获取任何数据.

How do I get the column names of a table into a PHP array using the mysqli extension? I need to fetch the column names of any given table without fetching any data from the table.

推荐答案

以下代码从table_name表中获取所有列名:

The following code gets all column names from table 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'];
}

因为我的表中有 idname 列,所以结果如下:

Since I have the columns id and name in my table, this is the result:

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]);
}

$columns 的示例结果:

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

$values 的示例结果:

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

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

)

这篇关于如何从给定的 MySQL 表中获取列名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆