且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-13 19:54:55

以下代码从表 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'];
}

由于我的表中有列 id name ,因此结果如下:

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
        )

)