Get table column names in MySQL?

2019-01-01 04:50发布

Is there a way to grab the columns name of a table in mysql? using php

标签: php sql mysql
17条回答
一个人的天荒地老
2楼-- · 2019-01-01 05:11

The MySQL function describe table should get you where you want to go (put your table name in for "table"). You'll have to parse the output some, but it's pretty easy. As I recall, if you execute that query, the PHP query result accessing functions that would normally give you a key-value pair will have the column names as the keys. But it's been a while since I used PHP so don't hold me to that. :)

查看更多
查无此人
3楼-- · 2019-01-01 05:13

This solution is from command line mysql

mysql>USE information_schema;

In below query just change <--DATABASE_NAME--> to your database and <--TABLENAME--> to your table name where you just want Field values of DESCRIBE statement

mysql> SELECT COLUMN_NAME FROM COLUMNS WHERE TABLE_SCHEMA = '<--DATABASE_NAME-->' AND   TABLE_NAME='<--TABLENAME-->';
查看更多
心情的温度
4楼-- · 2019-01-01 05:14

I have write a simple php script to fetch table columns through PHP: Show_table_columns.php

Enjoy!

查看更多
笑指拈花
5楼-- · 2019-01-01 05:15

There's also this if you prefer:

mysql_query('SHOW COLUMNS FROM tableName'); 
查看更多
怪性笑人.
6楼-- · 2019-01-01 05:21

this worked for me..

$sql = "desc MyTableName";
$result = @mysql_query($sql);
while($row = @mysql_fetch_array($result)){
    echo $row[0]."<br>";
}
查看更多
旧时光的记忆
7楼-- · 2019-01-01 05:22

I made a PDO function which returns all the column names in an simple array.

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

The output will be an array:

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

Sorry for the necro but I like my function ;)

P.S. I have not included the class Core but you can use your own class.. D.S.

查看更多
登录 后发表回答