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:
<code class="language-php">$query = "DESCRIBE my_table"; $result = $connection->query($query); while ($row = $result->fetch_assoc()) { echo $row['Field'] . "\n"; }</code>
<code class="language-php">$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"; }</code>
<code class="language-php">$query = "SHOW COLUMNS FROM my_table"; $result = $connection->query($query); while ($row = $result->fetch_assoc()) { echo $row['Field'] . "\n"; }</code>
To concatenate the column names into a single row separated by commas, you can use the following query:
<code class="language-php">$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];</code>
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!