What is the best method to output column names from an SQL table in PHP?

When working with SQL tables in PHP, you may need to output the column names of a table. One way to achieve this is by querying the information_schema database, specifically the COLUMNS table, to retrieve the column names of a specified table. Once you have fetched the column names, you can output them using PHP.

<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Query to fetch column names
$sql = "SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = '$dbname' AND TABLE_NAME = 'your_table_name'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output column names
    while($row = $result->fetch_assoc()) {
        echo $row["COLUMN_NAME"] . "<br>";
    }
} else {
    echo "No columns found for the specified table";
}

$conn->close();
?>