MySQL query to get column names?

前端 未结 21 2147
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 01:56

I\'d like to get all of a mysql table\'s col names into an array in php?

Is there a query for this?

21条回答
  •  伪装坚强ぢ
    2020-11-22 02:46

    The call of DESCRIBE is working fine to get all columns of a table but if you need to filter on it, you need to use the SHOW COLUMNS FROM instead.

    Example of PHP function to get all info of a table :

    // get table columns (or return false if table not found)
    function get_table_columns($db, $table) {
        
        global $pdo;
    
        if($cols = $pdo->query("DESCRIBE `$db`.`$table`")) {
            if($cols = $cols->fetchAll(PDO::FETCH_ASSOC)) {
                return $cols;
            }
        }
        
        return false;
    }
    

    In my case, I had to find the primary key of a table. So, I used :

    SHOW COLUMNS FROM `table` WHERE `Key`='PRI';
    

    Here is my PHP function :

    // get table Primary Key
    function get_table_pk($db, $table) {
    
        global $pdo;
                
        $q = "SHOW COLUMNS FROM `$db`.`$table` WHERE `Key` = 'PRI'";
        if($cols = $pdo->query($q)) {
            if($cols = $cols->fetchAll(PDO::FETCH_ASSOC)) {
                return $cols[0];
            }
        }
        
        return false;
    }
    

提交回复
热议问题