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
Release: 2024-11-03 12:36:02
Original
358 people have browsed it

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

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template