如何从给定的MySQL表中获取列名? [英] How do I get column names from a given MySQL table?
本文介绍了如何从给定的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'];
}
由于我的表中有列 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
)
)
这篇关于如何从给定的MySQL表中获取列名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文