使用PHP从mysql导出到csv时获取列名

时间:2019-01-15 05:31:10

标签: php mysql csv

我正在尝试将表从mysql db导出到csv。我能够成功完成此操作,但是,它不导出列名,请问有什么方法可以实现吗?有些指针会很棒。请检查取出下面的data_export.php文件:

<?php
include 'class.user.php';

$conn=mysqli_connect("localhost","root","PASSWORD","reflective");

#declare the school variable for use in the select* query
$school = $_POST['school'];

#query the students table for data to export
$select="SELECT * FROM students WHERE school_id ='$school'";


$result = mysqli_query($conn, $select);
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysqli_num_fields($result);


$headers ="";
while ($property = mysqli_fetch_field($result)) {
    $headers.= $property->name.",";    
}
$headers.="\n";


$fp = fopen('php://output', 'w');
if ($fp && $result) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="students_data.csv"');
    header('Pragma: no-cache');
    header('Expires: 0');
    fputcsv($fp, $headers);
    while ($row = $result->fetch_array(MYSQLI_NUM)) {
        fputcsv($fp, array_values($row));
    }
    die;
}
?>

1 个答案:

答案 0 :(得分:0)

我建议您在PHP中使用array_keys()方法。它将从您从数据库中获取的数组中提取所有键。您只需要在这样的方法中将第一个数组作为参数传递,

array_keys($data[0]);