Home >Database >Mysql Tutorial >How to Retrieve MySQL Table Column Names in PHP?

How to Retrieve MySQL Table Column Names in PHP?

Susan Sarandon
Susan SarandonOriginal
2025-01-17 22:48:11379browse

How to Retrieve MySQL Table Column Names in PHP?

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:

  1. DESCRIBE:
<code class="language-php">$query = "DESCRIBE my_table";
$result = $connection->query($query);
while ($row = $result->fetch_assoc()) {
    echo $row['Field'] . "\n";
}</code>
  1. INFORMATION_SCHEMA:
<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>
  1. SHOW COLUMNS:
<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn