SitePoint Sponsor

User Tag List

Results 1 to 16 of 16

Threaded View

  1. #1
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Burlington, Canada
    89 Post(s)
    2 Thread(s)

    Get PDO Column name - the easy way :)


    Czaries wrote this post regarding Column Meta Attributes... his method works well; however I needed something simpler so I wrote 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.

    Keep in mind:

    • $this->table_name is a property in my Crud Class so change it to your own property name or variable
    • $this->dbc should be a PDO object; again rename it if you don't like it.
    • $this->column_names is a property in my Crud Class so you can return it (once it has been propagated; you can return it directly or just change it to a name you prefer.
    • Yes I know that it is simple and most of you already know this; however there are always some lurkers in need right .
    • [edit] As sweatje points out (below) this works only for MySQL PDO driver.

    PHP Code:
    function getColumnNames(){
    $sql 'SHOW COLUMNS FROM ' $this->table_name;
    $this->stmt $this->dbc->prepare($sql);
            try {    
    $raw_column_data $this->stmt->fetchAll();
    $raw_column_data as $outer_key => $array){
    $array as $inner_key => $value){
                            if (
    $inner_key === 'Field'){
                                    if (!(int)
    $this->column_names[] = $value;
            } catch (
    Exception $e){
    $e->getMessage(); //return exception
    Last edited by ServerStorm; Jul 13, 2008 at 20:00.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts