首页 >数据库 >mysql教程 >如何在 PHP 中检索 MySQL 表列名?

如何在 PHP 中检索 MySQL 表列名?

Susan Sarandon
Susan Sarandon原创
2025-01-17 22:48:11379浏览

How to Retrieve MySQL Table Column Names in PHP?

从MySQL表中获取列名

PHP 提供多种方法来检索MySQL表的列名,方便开发者访问元数据以用于各种用途。这些方法包括:

  1. DESCRIBE:
<code class="language-php">$query = "DESCRIBE my_table";
$result = $connection->query($query);
while ($row = $result->fetch_assoc()) {
    echo $row['Field'] . "\n";
}</code>
  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>
  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>

为了将列名连接成以逗号分隔的单行,可以使用以下查询:

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

以上是如何在 PHP 中检索 MySQL 表列名?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn