Home > Database > Mysql Tutorial > How Can I Retrieve Column Names from a MySQL Table in PHP?

How Can I Retrieve Column Names from a MySQL Table in PHP?

Mary-Kate Olsen
Release: 2025-01-17 22:26:09
Original
348 people have browsed it

How Can I Retrieve Column Names from a MySQL Table in PHP?

Retrieve column names from MySQL table in PHP

Retrieving column names from a MySQL table is a common task in PHP programming. Here are a few ways to do this:

USE DESCRIBE

DESCRIBE command provides information about the table structure, including its column names.

<code class="language-php">$sql = "DESCRIBE my_table";
$result = $connection->query($sql);
while ($row = $result->fetch_assoc()) {
    echo $row['Field'] . "<br></br>"; // 显示列名
}</code>
Copy after login

Use INFORMATION_SCHEMA

The INFORMATION_SCHEMA database contains metadata about the MySQL database, including column names.

<code class="language-php">$sql = "SELECT COLUMN_NAME
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table'";
$result = $connection->query($sql);
while ($row = $result->fetch_assoc()) {
    echo $row['COLUMN_NAME'] . "<br></br>"; // 显示列名
}</code>
Copy after login

USE SHOW COLUMNS

SHOW COLUMNS command displays information about table columns, including their names.

<code class="language-php">$sql = "SHOW COLUMNS FROM my_table";
$result = $connection->query($sql);
while ($row = $result->fetch_assoc()) {
    echo $row['Field'] . "<br></br>"; // 显示列名
}</code>
Copy after login

Connect column name

If you want to retrieve the column names as comma separated strings, you can use the following query:

<code class="language-php">$sql = "SELECT group_concat(COLUMN_NAME)
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table'";
$result = $connection->query($sql);
$row = $result->fetch_assoc();
echo $row['group_concat(COLUMN_NAME)']; // 显示连接的列名</code>
Copy after login

The above is the detailed content of How Can I Retrieve Column Names from a MySQL Table in 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