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'];
}
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]);
}
Example result for $columns
:
Array
(
[0] => id
[1] => name
)
Example result for $values
:
Array
(
[0] => Array
(
[id] => 1
[name] => Name 1
)
[1] => Array
(
[id] => 2
[name] => Name 2
)
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…