SitePoint Sponsor

User Tag List

Results 1 to 16 of 16

Threaded View

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

    Get PDO Column name - the easy way :)

    Hi

    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 {    
                if(
    $this->stmt->execute()){
                    
    $raw_column_data $this->stmt->fetchAll();
                    
                    foreach(
    $raw_column_data as $outer_key => $array){
                        foreach(
    $array as $inner_key => $value){
                                
                            if (
    $inner_key === 'Field'){
                                    if (!(int)
    $inner_key){
                                        
    $this->column_names[] = $value;
                                    }
                                }
                        }
                    }        
                }
                return 
    true;
            } catch (
    Exception $e){
                    return 
    $e->getMessage(); //return exception
            
    }        
        } 
    Cheers,
    ServerStorm
    Last edited by ServerStorm; Jul 13, 2008 at 20:00.
    ictus==""


Bookmarks

Posting Permissions

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