如何在PHP MySQLi中获取列名? [英] How do I get Column Names in Php MySQLi?
本文介绍了如何在PHP MySQLi中获取列名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Php和MySQLi如何获取表的列名,然后将该查询的结果放入数组中?
Using Php and MySQLi how do I get the column names of a table and then put the result of that query in an array?
推荐答案
以下代码从表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
)
)
这篇关于如何在PHP MySQLi中获取列名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文