2013-07-22 83 views
0

如何在PHP中執行此操作?在csv formate中導出表數據並存儲到文件夾

我不想在csv文件中導出表格數據,而是在備份文件夾中存儲csv文件。

此我使用此:

$query = "SELECT * FROM `login_details`"; 
$file_name = "login_details"; 
$sql_csv = mysql_query($query) or die("Error: " . mysql_error()); //Replace this line with what is appropriate for your DB abstraction layer 

header("Content-type:text/octect-stream"); 
$done = header("Content-Disposition:attachment;filename=$fileName"); 

while($row = mysql_fetch_row($sql_csv)) { 
    print '"' . stripslashes(implode('","',$row)) . "\"\n"; 
} 

感謝。

+1

你應該看看[fputcsv()](http://www.php.net/manual/fr/function.fputcsv.php) – Brewal

回答

0

如果您的備份文件夾的位置(或可位於)在同一臺機器上的MySQL我正在競選然後實現自己的目標的最快,最簡單的方法是使用SELECT ... INTO OUTFILE條款

SELECT * 
    FROM login_details 
    INTO OUTFILE '/path/to/backup/folder/login_details.csv' 
     FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' 
     LINES TERMINATED BY '\n' -- or \r\n 

PHP代碼

$sql = "SELECT * 
      FROM login_details 
      INTO OUTFILE '/path/to/backup/folder/login_details.csv' 
       FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' 
       LINES TERMINATED BY '\n'"; 
$result = mysql_query($sql); 
if (!$result) { 
    die('Error: ' . mysql_error()); //TODO better error handling 
} 

在一個側面說明:mysql_*擴展已被棄用。考慮切換到mysqli或PDO。

+0

@ user1653938它是否幫助? – peterm

0

您可以使用fputcsv來做到這一點。這裏有功能手冊:http://php.net/manual/en/function.fputcsv.php

$query = "SELECT * FROM `login_details`"; 
$file_name = "login_details"; 
$sql_csv = mysql_query($query) or die("Error: " . mysql_error()); //Replace this line with what is appropriate for your DB abstraction layer 

$fp = fopen('cvsfile.csv', 'w'); 
while($row = mysql_fetch_row($sql_csv)) { 
    fputcsv($fp, split(',', $row)); 
} 
fclose($fp); 
相關問題