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

How to Fetch MySQL Table Column Names Using PHP?

Patricia Arquette
Release: 2025-01-17 22:31:10
Original
498 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template