从MySQL表中获取列名
PHP 提供多种方法来检索MySQL表的列名,方便开发者访问元数据以用于各种用途。这些方法包括:
<code class="language-php">$query = "DESCRIBE my_table"; $result = $connection->query($query); while ($row = $result->fetch_assoc()) { echo $row['Field'] . "\n"; }</code>
<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>
<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中文网其他相关文章!