如果我在 mysql_query
命令中使用以下内容:
SELECT *
FROM mytable
INTO OUTFILE '/tmp/mytable.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
- tmp 文件相对于 MySQL 数据库或 PHP 文件在哪里?
- 如果不存在会创建吗?
- 如果我希望它显示在执行它的 PHP 文件的上一级文件夹中,我该怎么做?
最佳答案
根据 The Documentation On Select ,它存储在服务器上而不是客户端上:
The SELECT ... INTO OUTFILE 'file_name' form of SELECT writes the selected rows to a file. The file is created on the server host, so you must have the FILE privilege to use this syntax. file_name cannot be an existing file, which among other things prevents files such as /etc/passwd and database tables from being destroyed. As of MySQL 5.0.19, the character_set_filesystem system variable controls the interpretation of the file name.
更重要的是:
The SELECT ... INTO OUTFILE statement is intended primarily to let you very quickly dump a table to a text file on the server machine. If you want to create the resulting file on some other host than the server host, you normally cannot use SELECT ... INTO OUTFILE since there is no way to write a path to the file relative to the server host's file system.
因此,请勿在生产中使用它来生成 CSV 文件。相反,使用 fputcsv
在 PHP 中构建 CSV :
$result = $mysqli->query($sql);
if (!$result) {
//SQL Error
}
$f = fopen('mycsv.csv', 'w');
if (!$f) {
// Could not open file!
}
while ($row = $result->fetch_assoc()) {
fputcsv($f, $row);
}
fclose($f);
关于PHP MySQL OUTFILE 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4783980/