PHP MySQL OUTFILE 命令

标签 php mysql

如果我在 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/

相关文章:

php - 连接同一服务器上的两个相似数据库

mysql - 将 MySQL 用户定义变量与 CakePHP3 查询选择结合使用

php - 制作类(class)预订系统PHP

php - 如何将用户从 php 文件重定向回 dreamhost 上的 `index.html`

php - 如何在我的 Xcode 项目中显示和使用 php 文件?

javascript - 如何使用 jquery 或 javascript 获取具有相同名称属性的多个字段的值?

javascript - 如何清除加载ajax的表单?

MySQL 日期和时间操作

MySQL 如何在求和中使用减法

java - Google App Engine 留言簿示例无法工作,无法连接到数据库