簡體   English   中英

使用PHP從mysql導出到csv時獲取列名

[英]get column names when exporting from mysql to csv using PHP

我正在嘗試將表從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; } ?> 

我建議您在PHP中使用array_keys()方法。 它將從您從數據庫中獲取的數組中提取所有鍵。 您只需要像這樣在方法中傳遞第一個數組作為參數,

array_keys($data[0]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM