Jump to content

Recommended Posts

Hello all. I have a script that exports data from mysql to a csv file. Everything works great. However, I do not know how to save the csv file to the server. Does anyone have any ideas how I would do that? The script is below. Thanks for all help!

 

<?php
$host = 'localhost';
$user = '';
$pass = '';
$db = '';
$table = '';
$file = 'export';

function escape_csv_value($value) { 
$value = str_replace('"', '""', $value); // First off escape all " and make them "" 
if(preg_match('/,/', $value) or preg_match("/n/", $value) or preg_match('/"/', $value)) { // Check if I have any commas or new lines 
return '"'.$value.'"'; // If I have new lines or commas escape them 
} else { 
return $value; // If no new lines or commas just return the value 
} 
} 


$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "\n";

$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= escape_csv_value($rowr[$j]).','; 
//$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}

$filename = $file."_".date("Y-m-d_H-i",time());
//header( "Content-Type: application/save-as" ); 

header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: attachment; filename=".$filename.".csv"); 




//header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>

Link to comment
https://forums.phpfreaks.com/topic/237328-save-csv-file-to-server/
Share on other sites

Ah yes. I didn't take too much notice of what the contents of $filename were before, but later in the code you're separately adding the extension:

 

header( "Content-disposition: attachment; filename=".$filename.".csv");

 

Either add the extension when you originally define $filename (removing it from lines like above) or just do the same for the file_put_contents() call.

I am now trying to ftp the saved file to a remote server but can't seem to get it to work. The following is the code I have for that --

 

//FTP file to remote server

     

  $ftpStream = ftp_connect("ftp.domain.com");

$loginResult = ftp_login($ftpStream, "username@domain.com", "password");

if ($loginResult) {

  ftp_put($ftpStream, "target.txt", "target.txt", FTP_ASCII);

}

ftp_quit($ftpStream);

  • 4 weeks later...

Just to share some alternative to this CSV file creation script.... another alternative way to do it  is just using the syntax:

SELECT .... INTO OUTFILE ...

 

only requirement is that the user  must have FILE privileges in the DB... a working example:

<?php

   // Define how to display/report errors in your development environment
   error_reporting(E_ALL);
   ini_set("display_errors", "1");
   
   $host = 'localhost';
   $user = 'yourusername';
   $pass = 'yourpassword';
   $db = 'yourdb';
   $table = 'yourtable';
   $file = "path where you want your file"  // p.e: "C:\\\stats-export2.csv"."_".date("Y-m-d_H-i",time());



   $link = mysql_connect($host, $user, $pass) or trigger_error("Can not connect." . mysql_error(), E_USER_ERROR);
   mysql_select_db($db) or trigger_error("DB not selected." . mysql_error(), E_USER_ERROR);

   $query = "SELECT * INTO OUTFILE '{$file}'
     FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
     LINES TERMINATED BY '\n'
     FROM $table";

   // var_dump($query);  // for debugging purposes only
   $values = mysql_query($query) or trigger_error("Error : ".mysql_error(), E_USER_ERROR);

   if ($values) {
      // File Generated OK
      echo "Ok";
   } else {
      // Something was wrong
      echo "No-OK";
   }   
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.