Home >Backend Development >PHP Tutorial >How to Retrieve Table Column Names Using PDO in MySQL?

How to Retrieve Table Column Names Using PDO in MySQL?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 12:36:02343browse

How to Retrieve Table Column Names Using PDO in MySQL?

Retrieving Table Column Names with PDO

Question:

How do I retrieve the column names of a table using PDO?

Context:

Consider a table named "contacts" with the following columns:

  • id
  • name
  • age

Attempt:

An attempt was made using the following code:

<code class="php">$db = $connection->get_connection();
$select = $db->query('SELECT * FROM contacts');

$total_column = $select->columnCount();
var_dump($total_column);

for ($counter = 0; $counter < $total_column; $counter ++) {
    $meta = $select->getColumnMeta($counter);
    $column[] = $meta['name'];
}
print_r($column);</code>

However, this attempt produced an unexpected result, returning all column names, including non-existent columns.

Solution (MySQL-specific):

An alternative solution for MySQL databases is as follows:

<code class="php">$table_fields = $dbh->query("DESCRIBE tablename")->fetchAll(PDO::FETCH_COLUMN);</code>

This query retrieves the table's column names using the "DESCRIBE" command. The result is an array containing the column names in the order they appear in the table's schema.

Output:

Array
(
    [0] => id
    [1] => name
    [2] => age
    ...
)

The above is the detailed content of How to Retrieve Table Column Names Using PDO in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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