MySQL query to get column names?

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

    This question is old, but I got here looking for a way to find a given query its field names in a dynamic way (not necessarily only the fields of a table). And since people keep pointing this as the answer for that given task in other related questions, I'm sharing the way I found it can be done, using Gavin Simpson's tips:

    //Function to generate a HTML table from a SQL query
    function myTable($obConn,$sql)
    {
        $rsResult = mysqli_query($obConn, $sql) or die(mysqli_error($obConn));
        if(mysqli_num_rows($rsResult)>0)
        {
            //We start with header. >>>Here we retrieve the field names<<<
            echo "<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"0\"><tr align=\"center\" bgcolor=\"#CCCCCC\">";
            $i = 0;
            while ($i < mysqli_num_fields($rsResult)){
               $field = mysqli_fetch_field_direct($rsResult, $i);
               $fieldName=$field->name;
               echo "<td><strong>$fieldName</strong></td>";
               $i = $i + 1;
            }
            echo "</tr>"; 
            //>>>Field names retrieved<<<
    
            //We dump info
            $bolWhite=true;
            while ($row = mysqli_fetch_assoc($rsResult)) {
                echo $bolWhite ? "<tr bgcolor=\"#CCCCCC\">" : "<tr bgcolor=\"#FFF\">";
                $bolWhite=!$bolWhite;
                foreach($row as $data) {
                    echo "<td>$data</td>";
                }
                echo "</tr>";
            }
            echo "</table>";
        }
    }
    

    This can be easily modded to insert the field names in an array.

    Using a simple: $sql="SELECT * FROM myTable LIMIT 1" can give you the fields of any table, without needing to use SHOW COLUMNS or any extra php module, if needed (removing the data dump part).

    Hopefully this helps someone else.

    0 讨论(0)
  • 2020-11-22 02:54

    The best way is to use the INFORMATION_SCHEMA metadata virtual database. Specifically the INFORMATION_SCHEMA.COLUMNS table...

    SELECT `COLUMN_NAME` 
    FROM `INFORMATION_SCHEMA`.`COLUMNS` 
    WHERE `TABLE_SCHEMA`='yourdatabasename' 
        AND `TABLE_NAME`='yourtablename';
    

    It's VERY powerful, and can give you TONS of information without need to parse text (Such as column type, whether the column is nullable, max column size, character set, etc)...

    Oh, and it's standard SQL (Whereas SHOW ... is a MySQL specific extension)...

    For more information about the difference between SHOW... and using the INFORMATION_SCHEMA tables, check out the MySQL Documentation on INFORMATION_SCHEMA in general...

    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题