MySQL query to get column names?

前端 未结 21 2427
伪装坚强ぢ
伪装坚强ぢ 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:54

    SHOW COLUMNS in mysql 5.1 (not 5.5) uses a temporary disk table.

    • http://dev.mysql.com/doc/refman/5.1/en/internal-temporary-tables.html
    • http://dev.mysql.com/doc/refman/5.1/en/show-columns.html

    So it can be considered slow for some cases. At least, it can bump up your created_tmp_disk_tables value. Imagine one temporary disk table per connection or per each page request.

    SHOW COLUMNS is not really so slow, possibly because it uses file system cache. Phpmyadmin says ~0.5ms consistently. This is nothing compared to 500ms-1000ms of serving a wordpress page. But still, there are times it matters. There is a disk system involvement, you never know what happens when server is busy, cache is full, hdd is stalled etc.

    Retrieving column names through SELECT * FROM ... LIMIT 1 was around ~0.1ms, and it can use query cache as well.

    So here is my little optimized code to get column names from a table, without using show columns if possible:

    function db_columns_ar($table)
    {
    //returns Array('col1name'=>'col1name','col2name'=>'col2name',...)
    if(!$table) return Array();
    if(!is_string($table)) return Array();
    
    global $db_columns_ar_cache;
    if(!empty($db_columns_ar_cache[$table]))
        return $db_columns_ar_cache[$table];
    
    
    //IMPORTANT show columns creates a temp disk table
    $cols=Array();
    $row=db_row_ar($q1="SELECT * FROM `$table` LIMIT 1");
    if($row)
        {
        foreach($row as $name=>$val)
            $cols[$name]=$name;
        }
    else
        {
        $coldata=db_rows($q2="SHOW COLUMNS FROM `$table`");
        if($coldata)
            foreach($coldata as $row)
                $cols[$row->Field]=$row->Field;
        }
    $db_columns_ar_cache[$table]=$cols;
    //debugexit($q1,$q2,$row,$coldata,$cols);
    return $cols;
    }
    

    Notes:

    • As long as your tables first row does not contain megabyte range of data, it should work fine.
    • The function names db_rows and db_row_ar should be replaced with your specific database setup.

提交回复
热议问题