Home > Backend Development > PHP Tutorial > How to Get Column Names from a Table Using PDO?

How to Get Column Names from a Table Using PDO?

DDD
Release: 2024-11-04 01:39:02
Original
820 people have browsed it

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>
Copy after login

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
)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template