Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySQL OUTFILE command

Tags:

php

mysql

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?
like image 508
David19801 Avatar asked Apr 11 '26 21:04

David19801


2 Answers

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);
like image 186
ircmaxell Avatar answered Apr 14 '26 11:04

ircmaxell


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"

like image 35
Sigtran Avatar answered Apr 14 '26 11:04

Sigtran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!