简体   繁体   中英

get column names when exporting from mysql to csv using PHP

I am trying to export a table from a mysql db to csv.I am able to do this successfully,however, it doesnt export the column names,is there any way i achieve this?Some pointers would be great.Please check out my data_export.php file below:

 <?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; } ?> 

I would suggest you use the array_keys() method in PHP. It will extract all the keys from the array you fetch from the database. You just need to pass the first array as argument in the method like this,

array_keys($data[0]);

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