如何在PHP中执行此操作?
我不想只导出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";
}
感谢。
答案 0 :(得分:0)
你必须打开文件写(句柄)使用http://php.net/manual/en/function.fopen.php
使用创建的句柄来编写字符串http://php.net/manual/en/function.fputcsv.php
完成后关闭句柄(参见doc for fopen)使用fclose()
例如:
//you code to get data from sql
$handle = fopen('full path to store (you can use ftp etd)', 'w'); // see mode
while($row = mysql_fetch_row($sql_csv)) {
fputcsv($handle, $row);
}
fclose($handle);
答案 1 :(得分: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 code
$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。
答案 2 :(得分: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);