Home > Article > Backend Development > How to Get Column Names from a Table Using PDO?
Get Column Names from a Table Using PDO
Obtaining the column names of a table is a common task when working with databases. With PHP's PDO extension, it can be achieved with a few lines of code.
Assuming a table named 'contacts' with columns 'id', 'name', and 'age', here's how you can fetch the column names:
<code class="php">$dbh = $connection->get_connection(); $stmt = $dbh->query("DESCRIBE contacts"); $table_fields = $stmt->fetchAll(PDO::FETCH_COLUMN);</code>
The DESCRIBE statement retrieves information about the table structure, and fetchAll(PDO::FETCH_COLUMN) returns an array containing only the first column of the result (the column names in this case).
This code would produce the following output:
Array ( [0] => id [1] => name [2] => age )
You can then use the $table_fields array to access the column names as needed.
The above is the detailed content of How to Get Column Names from a Table Using PDO?. For more information, please follow other related articles on the PHP Chinese website!