如何在 PHP MySQLi 中获取列名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38553573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get Column Names in Php MySQLi?
提问by benj rei
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?
使用 PHP 和 MySQLi 如何获取表的列名,然后将该查询的结果放入数组中?
回答by FirstOne
The following code gets all column names from table table_name
:
以下代码从 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'];
}
Since I have the columns id
and name
in my table, this is the result:
由于我有列id
和name
我的表,这是结果:
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
)
)
回答by jophab
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 数组包含表的列名