mysql获取表的列名

  时间:2017-07-28
本文章向大家介绍mysql获取表的列名,需要的朋友可以参考一下。

您可以使用DESCRIBE:

DESCRIBE my_table;

或者在较新的版本中,您可以使用INFORMATION_SCHEMA:

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';

或者您可以使用SHOW COLUMNS:

SHOW COLUMNS FROM my_table;

 

以下SQL语句几乎相同:

SELECT COLUMN_NAME
  FROM INFORMATION_SCHEMA.COLUMNS
 WHERE table_name = 'tbl_name'
  [AND table_schema = 'db_name']
  [AND column_name LIKE 'wild']

SHOW COLUMNS
FROM tbl_name
[FROM db_name]
[LIKE 'wild']

 

我做了一个PDO函数,它返回一个简单数组中的所有列名。

public function getColumnNames($table){
    $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table";
    try {
        $core = Core::getInstance();
        $stmt = $core->dbh->prepare($sql);
        $stmt->bindValue(':table', $table, PDO::PARAM_STR);
        $stmt->execute();
        $output = array();
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            $output[] = $row['COLUMN_NAME'];                
        }
        return $output; 
    }

    catch(PDOException $pe) {
        trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
    }
}

输出将是一个数组:

Array (
[0] => id
[1] => name
[2] => email
[3] => shoe_size
[4] => likes
... )

原文地址:http://www.manongjc.com/article/1961.html