1

I have a php page that takes my query results and saves them to a csv, which then prompts to download the csv file (all which is working fine). What I need is for the file to save in the same location on the server but I cannot seem to get it to work. Any idea how to save to the server rather than download?

<?php

// Database Connection

include "connection.php"; //Connect to Database

// Fetch Record from Database

$output = "";
$sql = mysql_query("select '$select' from'$from' where'$where'"
$columns_total = mysql_num_fields($sql);

// Get The Field Name

for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";

// Get Records from the table

while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}

// Download the file

$filename = "file.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
exit;
?>
user2168066
  • 627
  • 11
  • 21
  • If its just csv files you can use `fputcsv`. Do it before you output the headers. – frz3993 Jul 10 '15 at 20:51
  • If you can, you should [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) [statements](http://php.net/manual/en/pdo.prepared-statements.php) instead, and consider using PDO, [it's really not hard](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Jul 10 '15 at 20:51
  • why are you building csv manually? you should be using `fputcsv()`... – Marc B Jul 10 '15 at 21:26

1 Answers1

0

Just use file_put_contents() function to save your CSV file into your server:

file_put_contents('yourfile.csv', $output);

So your code would be like:

<?php

// Database Connection

include "connection.php"; //Connect to Database

// Fetch Record from Database

$output = "";
$sql = mysql_query("select '$select' from'$from' where'$where'"
$columns_total = mysql_num_fields($sql);

// Get The Field Name

for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";

// Get Records from the table

while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}

// Download the file

$filename = "file.csv";
file_put_contents($filename, $output);
Sky
  • 4,244
  • 7
  • 54
  • 83