简体   繁体   中英

column names from mysql to csv

Hey could anyone help me out. I'm creating a csv from mysql table for client side download. The data is inserting and formatting fine to the csv file but no column names? Any help would be much appreciated. I'm new to this so not too much ridicule please :)

$result = mysqli_query($con,'SELECT * FROM score15ans WHERE id_user = "'.$userID.'" ORDER BY pps');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysqli_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysqli_fetch_field($result, $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
    fputcsv($fp, array_values($row));
}
die;
}

Try

for ($i = 0; $i < $num_fields; $i++) {
    $headers[$i] = mysqli_fetch_assoc($result, $i);
    $headersField[$i] = $headers[$i]['Field'];
}

fputcsv($fp, $headersField);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM