2016-04-26 67 views
0

我正在用csv格式表示我的數據庫,但我無法弄清楚如何導出mysql表列名稱。下面是代碼:從數據庫中獲取mysql表列名稱當導出到csv

public function save($query) 
    { 
     $stmt = $this->db->prepare($query); 
     $stmt->execute(); 

     /* header("Content-type: text/csv"); 
     header("Content-Disposition: attachment; filename=file.csv"); 
     header("Pragma: no-cache"); 
     header("Expires: 0"); 

     var_dump($stmt->fetch(PDO::FETCH_ASSOC)); 
     $data = fopen('/tmp/db_user_export_".time().".csv', 'w'); 
     while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ 
      echo "Success"; 
      fputcsv($data, $row); 
     } */ 

     $list = array(); 

      // Append results to array 
      array_push($list, array("## START OF USER TABLE ##")); 
      while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
       array_push($list, array_values($row)); 
      } 
      array_push($list, array("## END OF USER TABLE ##")); 

      // Output array into CSV file 
      $fp = fopen('php://output', 'w'); 
      header('Content-Type: text/csv'); 
      header('Content-Disposition: attachment; filename="file.csv"'); 
      foreach ($list as $ferow) { 
       fputcsv($fp, $ferow); 
      } 

    } 

爲查詢:

include_once 'dbconfig.php'; 
$query = "SELECT * FROM users"; 
$crud->save($query); 

的FILE.CSV出口正常,但我想也包括MySQL表列的名字從那裏正在採取的值從。

在此先感謝!

+0

見http://stackoverflow.com/questions/4165195/mysql-query-to-get-column-names – dbugger

回答

0

我有問題張貼我的表頭到CSV,所以我採取了另一種方法。希望它幫助了試圖做我在做什麼的人:

public function export($table) 
    { 

     $stmt2 = $this->db->prepare("DESCRIBE ".$table); 
     $stmt2->execute(); 

     if ($stmt2->rowCount()>0) { 
     while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)) { 
      $csv_output .= $row['Field'].", "; 
      $i++; 
     } 
     } 
     $csv_output .= "\n"; 

     $stmt3 = $this->db->prepare("SELECT * FROM ".$table); 
     $stmt3->execute(); 

     while ($rowr = $stmt3->fetch(PDO::FETCH_BOTH)) { 
     for ($j=0;$j<$i;$j++) { 
      $csv_output .= $rowr[$j].", "; 
     } 
     $csv_output .= "\n"; 
     } 

     $filename = "raport_proiecte_".date("Y-m-d_H-i",time()).".csv"; 
     header("Content-Type: application/xls");  
     header("Content-Disposition: attachment; filename=$filename"); 
     header("Pragma: no-cache"); 
     header("Expires: 0"); 
     print $csv_output; 
     exit; 

    } 
相關問題