Home >Database >Mysql Tutorial >How to Fetch MySQL Table Column Names Using PHP?

How to Fetch MySQL Table Column Names Using PHP?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-17 22:31:10500browse

How to Fetch MySQL Table Column Names Using PHP?

Accessing MySQL Table Column Names with PHP

This guide demonstrates several PHP methods for retrieving column names from a MySQL table.

Method 1: Using DESCRIBE

The DESCRIBE command offers a concise approach:

<code class="language-php">$query = "DESCRIBE my_table";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
  echo $row['Field'] . "<br></br>";
}</code>

Method 2: Leveraging INFORMATION_SCHEMA

The INFORMATION_SCHEMA provides a more structured method:

<code class="language-php">$query = "SELECT COLUMN_NAME
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table'";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
  echo $row['COLUMN_NAME'] . "<br></br>";
}</code>

Method 3: Employing SHOW COLUMNS

The SHOW COLUMNS command is another efficient option:

<code class="language-php">$query = "SHOW COLUMNS FROM my_table";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
  echo $row['Field'] . "<br></br>";
}</code>

Method 4: Generating a Comma-Separated List

For a comma-separated string of column names:

<code class="language-php">$query = "SELECT GROUP_CONCAT(COLUMN_NAME)
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table'";
$result = $mysqli->query($query);
$row = $result->fetch_row();
echo $row[0];</code>

The above is the detailed content of How to Fetch MySQL Table Column Names Using 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