How to get the columns names along with resultset in php/mysql?

后端 未结 5 1171
生来不讨喜
生来不讨喜 2020-12-06 05:56

Is this OK ?

$i = 0;
while ($row = mysql_fetch_array($result))
{
    $resultset[] = $row;
    $columns[] = mysql_fetch_field($result, $i);
}
<
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 06:23

    Use mysql_fetch_assoc to get only an associative array and retrieve the column names with the first iteration:

    $columns = array();
    $resultset = array();
    while ($row = mysql_fetch_assoc($result)) {
        if (empty($columns)) {
            $columns = array_keys($row);
        }
        $resultset[] = $row;
    }
    

    Now you can print the head of your table with the first iteration as well:

    echo '';
    $columns = array();
    $resultset = array();
    while ($row = mysql_fetch_assoc($result)) {
        if (empty($columns)) {
            $columns = array_keys($row);
            echo '';
        }
        $resultset[] = $row;
        echo '';
    }
    echo '
    '.implode('', $columns).'
    '.implode('', $rows).'
    ';

提交回复
热议问题