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>
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>
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>
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>
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!