Home > Database > Mysql Tutorial > How to Retrieve MySQL Table Column Names in PHP?

How to Retrieve MySQL Table Column Names in PHP?

Susan Sarandon
Release: 2025-01-17 22:48:11
Original
377 people have browsed it

How to Retrieve MySQL Table Column Names in PHP?

Get column names from MySQL table

PHP provides multiple methods to retrieve column names of MySQL tables, making it easy for developers to access metadata for various purposes. These methods include:

  1. DESCRIBE:
<code class="language-php">$query = "DESCRIBE my_table";
$result = $connection->query($query);
while ($row = $result->fetch_assoc()) {
    echo $row['Field'] . "\n";
}</code>
Copy after login
  1. INFORMATION_SCHEMA:
<code class="language-php">$query = "SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table'";
$result = $connection->query($query);
while ($row = $result->fetch_assoc()) {
    echo $row['COLUMN_NAME'] . "\n";
}</code>
Copy after login
  1. SHOW COLUMNS:
<code class="language-php">$query = "SHOW COLUMNS FROM my_table";
$result = $connection->query($query);
while ($row = $result->fetch_assoc()) {
    echo $row['Field'] . "\n";
}</code>
Copy after login

To concatenate the column names into a single row separated by commas, you can use the following query:

<code class="language-php">$query = "SELECT GROUP_CONCAT(COLUMN_NAME SEPARATOR ',')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table'";
$result = $connection->query($query);
$row = $result->fetch_row();
echo $row[0];</code>
Copy after login

The above is the detailed content of How to Retrieve MySQL Table Column Names 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