從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中文網其他相關文章!