2010-08-11 239 views
0

我需要將此查詢的結果導出爲.csv,以便我可以創建圖表我只是沒有任何想法如何去做,而我仍然半新到PHP感謝任何幫助。將查詢導出爲CSV

$query="SELECT familyID, Fam_End_Date, Fam_Start_Date, 
     DATEDIFF(date(Fam_End_Date), date(Fam_Start_Date)) 
     AS Days_Between, 
     TIMEDIFF(time(Fam_Start_Date), time(Fam_End_Date)) 
     AS Time_Between 
     FROM family 
     WHERE Fam_End_Date IS NOT NULL 
     AND Fam_Start_Date IS NOT NULL 
     AND year(Fam_Start_Date)='$year'"; 
     $result = mysql_db_query($aidDB, $query, $connection); 

回答

2

嘗試遍歷結果集並使用fputcsv將行寫入文件。 http://php.net/manual/en/function.fputcsv.php

例如:

//continuing from your code above: 
$fp = fopen('file.csv', 'w'); 

while ($row = mysql_fetch_assoc($result)) { 
    fputcsv($fp,$row); 
} 

fclose($fp); 
+0

我加入你的代碼,也嘗試過安迪的代碼,並得到這個錯誤 警告:fopen(file.csv):未能打開流:權限被拒絕在線19 致命錯誤:調用未定義的函數:fputcsv()0n第22行 – 2010-08-11 16:04:26

+0

Karl,您正在寫入的文件是否存在? (也就是說,您是否已經創建了一個名爲「file.csv」的文件? – Irwin 2010-08-11 16:15:23