Get column names from MySQL table
PHP provides multiple methods to retrieve column names of MySQL tables, making it easy for developers to access metadata for various purposes. These methods include:
$query = "DESCRIBE my_table"; $result = $connection->query($query); while ($row = $result->fetch_assoc()) { echo $row['Field'] . "\n"; }
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table'"; $result = $connection->query($query); while ($row = $result->fetch_assoc()) { echo $row['COLUMN_NAME'] . "\n"; }
$query = "SHOW COLUMNS FROM my_table"; $result = $connection->query($query); while ($row = $result->fetch_assoc()) { echo $row['Field'] . "\n"; }
To concatenate the column names into a single row separated by commas, you can use the following query:
$query = "SELECT GROUP_CONCAT(COLUMN_NAME SEPARATOR ',') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table'"; $result = $connection->query($query); $row = $result->fetch_row(); echo $row[0];
The above is the detailed content of How to Retrieve MySQL Table Column Names in PHP?. For more information, please follow other related articles on the PHP Chinese website!