Gibt es eine Möglichkeit, den Spaltennamen einer Tabelle in MySQL mit PHP zu erfassen?
Antworten
Zu viele Anzeigen?
duhaime
Punkte
22637
Ich brauchte Spaltennamen als flaches Array, während die anderen Antworten assoziative Arrays zurückgaben, also verwendete ich:
$con = mysqli_connect('localhost',$db_user,$db_pw,$db_name);
$table = 'people';
/**
* Get the column names for a mysql table
**/
function get_column_names($con, $table) {
$sql = 'DESCRIBE '.$table;
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row['Field'];
}
return $rows;
}
$col_names = function get_column_names($con, $table);
$col_names ist jetzt gleich:
(
[0] => name
[1] => parent
[2] => number
[3] => chart_id
[4] => type
[5] => id
)
Andy Hume
Punkte
38284
denny
Punkte
1864
Wolf Metzner
Punkte
73
Wie wäre es damit:
SELECT @cCommand := GROUP_CONCAT( COLUMN_NAME ORDER BY column_name SEPARATOR ',\n')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
SET @cCommand = CONCAT( 'SELECT ', @cCommand, ' from my_database.my_table;');
PREPARE xCommand from @cCommand;
EXECUTE xCommand;