php pdo: get the columns name of a table

pdo fetch column
php pdo fetch
php pdo::fetch single row
php pdo fetchall
how to fetch single column from database in php
pdo fetch single value
php pdo loop through results
php pdo mysql fetch array

How can I get all the column names from a table using PDO?

id         name        age
1          Alan        35      
2          Alex        52
3          Amy         15

The info that I want to get are,

id         name        age

EDIT:

Here is my attempt,

$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);

Then I get,

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

)

I solve the problem the following way (MySQL only)

$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);

PDOStatement::getColumnMeta - Manual, PDOStatement::getColumnMeta — Returns metadata for a column in a result set table, The name of this column's table as returned by the database. len, The  How can I get all the column names from a table using PDO? id name age 1 Alan 35 2 Alex 52 3 Amy 15


This will work for MySQL, Postgres, and probably any other PDO driver that uses the LIMIT clause.

Notice LIMIT 0 is added for improved performance:

$rs = $db->query('SELECT * FROM my_table LIMIT 0');
for ($i = 0; $i < $rs->columnCount(); $i++) {
    $col = $rs->getColumnMeta($i);
    $columns[] = $col['name'];
}
print_r($columns);

Get PDO Column name - the easy way :) - PHP, this method (that goes with a crud class) that someone may find handy if they are using PDO and would like to simply return all column names of a given table. But when there are 2 tables with the same name (in different databases) it fetches those column names as well. In the following query $table of course means the requested table. In this case for example customer. select column_name from information_schema.columns where lower(table_name)=lower(\''.$table.'\')


My 2 cents:

$result = $db->query('select * from table limit 1');
$fields = array_keys($result->fetch(PDO::FETCH_ASSOC));

And you will get the column names as an array in the var $fields.

php pdo: get the columns name of a table, How can I get all the column names from a table using PDO? id name age 1 Alan 35 2 Alex 52 3 Amy 15. The info that I want to get are, id name  Hi Czaries,. I'm a pragmatist, so usually even if I know there's a better way, I won't change something until I need to :). Ya, Kyber and others have many times said, find the simplest solution


$sql = "select column_name from information_schema.columns where table_name = 'myTable'";

PHP function credits : http://www.sitepoint.com/forums/php-application-design-147/get-pdo-column-name-easy-way-559336.html

    function getColumnNames(){ 

    $sql = "select column_name from information_schema.columns where table_name = 'myTable'";
    #$sql = 'SHOW COLUMNS FROM ' . $this->table; 

    $stmt = $this->connection->prepare($sql); 

    try {     
        if($stmt->execute()){ 
            $raw_column_data = $stmt->fetchAll(PDO::FETCH_ASSOC); 

            foreach($raw_column_data as $outer_key => $array){ 
                foreach($array as $inner_key => $value){ 
                            if (!(int)$inner_key){ 
                                $this->column_names[] = $value; 
                            } 
                } 
            } 
            } 
            return $this->column_names; 
        } catch (Exception $e){ 
                return $e->getMessage(); //return exception 
        }         
    }  

Get the structure of a MySQL table in PHP (PDO)., How to get the structure / column names of a MySQL table in PHP. MySQL Query to Get Column Names The following query will find the column names from a table in MySQL and returns all the columns of the specified table. SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'db_name' AND TABLE_NAME = 'tbl_name' Use TABLE_SCHEMA to select the columns of a table from a specific database.


Here is the function I use. Created based on @Lauer answer above and some other resources:

//Get Columns
function getColumns($tablenames) {
global $hostname , $dbnames, $username, $password;
try {
$condb = new PDO("mysql:host=$hostname;dbname=$dbnames", $username, $password);

//debug connection
$condb->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$condb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// get column names
$query = $condb->prepare("DESCRIBE $tablenames");
$query->execute();
$table_names = $query->fetchAll(PDO::FETCH_COLUMN);
return $table_names;

//Close connection
$condb = null;

} catch(PDOExcepetion $e) {
echo $e->getMessage();
}
}

Usage Example:

$columns = getColumns('name_of_table'); // OR getColumns($name_of_table); if you are using variable.

foreach($columns as $col) {
echo $col . '<br/>';
}

Php PDO Get all column names from table in specific database , In MySQL database is a synonym for schema. Subsequently, the information you'​re looking for is in the column table_schema : select column_name from  in mysql to get columns details and table structure by following keywords or queries. 1.DESC table_name. 2.DESCRIBE table_name. 3.SHOW COLUMNS FROM table_name. 4.SHOW create table table_name; 5.EXPLAIN table_name


PDO constants in a table - PHP Tutorials, Not valid inside PDOStatement::fetchAll(). integer. PDO::FETCH_ASSOC. Fetch method returns each row as an array indexed by column name in the result set. The PHP native type used to represent the column value. driver:decl_type: The SQL type used to represent the column value in the database. If the column in the result set is the result of a function, this value is not returned by PDOStatement::getColumnMeta(). flags: Any flags set for this column. name: The name of this column as returned by the database.


php pdo: get the columns name of a table, How can I get all the column names from a table using PDO? The DESCRIBE query will return an array of associative arrays, with each array representing a column in the table. This array will contain the following information: Field: The name of the field / column. Type: The type of column it is (VARCHAR, INT, TEXT, etc). Null: Whether the column can be NULL or not.


Fetching rows or columns from result sets in PHP (PDO), By default, PDO returns each row as an array indexed by the column name and 0​-indexed column position in the row. To request a different return style, specify  The general format of the PHP code to add all the rows of a column is shown The purpose of this code is to teach you on how to calculate the values of a column using the Sum function. This is very useful if you want to create a poin of sale system in your PHP project.