2013-12-11 176 views
0

所有這些都駐留在ubuntu LAMP服務器上。我試圖把一個sql查詢的結果放到一個csv文件中。 PHP可以查詢數據庫並創建csv文件。但我無法將結果寫入csv文件。將MYSQL查詢寫入CSV文件無法寫入查詢

<?php 
//connect to db and query 
$db_conn=mysqli_connect(xxxx, xxxx, xxxx, xxxx); 
if (mysqli_connect_errno($db_conn)) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 
$result = mysqli_query($db_conn,'SELECT time, bid, ask, volume FROM MtGox LIMIT 50'); 
$fp = fopen('/var/www/BTCData.csv',"w")or die("can't open file"); 

//store results as array and put into csv file 
$fp = fopen('/var/www/TempFile.csv',"w")or die("can't open file"); 
$row = mysqli_fetch_assoc($result)or die('failure!'); 
foreach ($row as $fields) { 
fputcsv($fp, $fields); 
} 
fclose($fp); 
echo 'success!'; 
?> 
+0

你應該把你的'mysqli_fetch_assoc'通話inmto環路,也或者你只能得到一個單行。另外 - 你打開兩個CSV文件;你想寫哪一個? – andrewsi

+0

我想寫給BTCData。問題似乎是從mysqli_fetch_assoc獲取數據。如果我在網頁上打印或回顯結果,所有行都會顯示出來。但是,我無法獲取到csv文件。我可以寫入目錄,因爲我已經將一些文本文件寫入了一些文本文件來檢查。 – user3092297

回答

0
$db_conn=mysqli_connect(xxxx, xxxx, xxxx, xxxx); 
if (mysqli_connect_errno($db_conn)) { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 
$result = mysqli_query($db_conn,'SELECT time, bid, ask, volume FROM MtGox LIMIT 50'); 
$data = ''; 

while ($row = mysql_fetch_assoc($result)) { 
    $data .= $row['time'].';'; 
    $data .= $row['bid'].';'; 
    $data .= $row['ask'].';'; 
    $data .= $row['volume'].';'; 
} 

file_put_contents ('/var/www/BTCData.csv', $data); 
+0

這會創建csv文件,但不會寫入任何內容。 – user3092297