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
Release: 2024-12-14 11:11:10
Original
663 people have browsed it

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>";
}
Copy after login

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>";
}
Copy after login

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>";
}
Copy after login

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)'];
Copy after login

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!

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