MySQL query to get column names?

前端 未结 21 2587
伪装坚强ぢ
伪装坚强ぢ 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 "";
            $i = 0;
            while ($i < mysqli_num_fields($rsResult)){
               $field = mysqli_fetch_field_direct($rsResult, $i);
               $fieldName=$field->name;
               echo "";
               $i = $i + 1;
            }
            echo ""; 
            //>>>Field names retrieved<<<
    
            //We dump info
            $bolWhite=true;
            while ($row = mysqli_fetch_assoc($rsResult)) {
                echo $bolWhite ? "" : "";
                $bolWhite=!$bolWhite;
                foreach($row as $data) {
                    echo "";
                }
                echo "";
            }
            echo "
    $fieldName
    $data
    "; } }

    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.

提交回复
热议问题