3

If I use the following in a mysql_query command:

SELECT *
FROM mytable
INTO OUTFILE '/tmp/mytable.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
  • Where is the tmp file relative to, to the MySQL database somehow or to the PHP file?
  • If it does not exist will it be created?
  • If I would like it to appear 1 folder up from the PHP file which does it, how would I do that?
1
  • The way you've written the path isn't a relative path. Commented Jan 24, 2011 at 15:57

3 Answers 3

3

According to The Documentation On Select, it's stored on the server and not on the client:

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.

And, more to the point:

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.

So, don't use it in production to generate CSV files. Instead, build the CSV in PHP using fputcsv:

$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);
Sign up to request clarification or add additional context in comments.

Comments

2

Where is the tmp file relative to?

A: The file will have the result of the select * from mytable

If it does not exist will it be created?

A: yes

If I would like it to appear 1 folder up from the php file which does it, how would I do that?

A: if you want one folder up from the fileYouAreRunning.php then make path like that: "../mytable.csv"

Comments

0

Your current query has an absolute path. So the outfile will not be relative to anything, but saved to /tmp/mytable.csv.

I'd say, the safest bet would be to keep useing absolute paths, so check in your php what your absolute path to the parent is, and then add this to your query using a variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.