Home >Backend Development >PHP Tutorial >How Can I Retrieve MySQL Table Column Names Using PHP?

How Can I Retrieve MySQL Table Column Names Using PHP?

Susan Sarandon
Susan SarandonOriginal
2024-12-14 11:11:10663browse

How Can I Retrieve MySQL Table Column Names Using PHP?

Retrieving Table Column Names in MySQL using PHP

In MySQL, there are several ways to retrieve the column names of a specific table using PHP. One method is to use theDESCRIBE statement:

$query = "DESCRIBE my_table";
$result = $conn->query($query);
while ($row = $result->fetch_assoc()) {
    echo $row['Field'] . "<br>";
}

Another option is to utilize the INFORMATION_SCHEMA table:

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

A third method involves using the SHOW COLUMNS statement:

$query = "SHOW COLUMNS FROM my_table";
$result = $conn->query($query);
while ($row = $result->fetch_assoc()) {
    echo $row['Field'] . "<br>";
}

Lastly, to obtain the column names separated by commas in a single line, you can use the following query:

$query = "SELECT group_concat(COLUMN_NAME)
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table'";
$result = $conn->query($query);
$row = $result->fetch_assoc();
echo $row['group_concat(COLUMN_NAME)'];

By employing these techniques, you can effortlessly retrieve column names from your MySQL tables within PHP code.

The above is the detailed content of How Can I Retrieve 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