使用php将mysql查询保存为远程ftp服务器上的csv文件

使用php将mysql查询保存为远程ftp服务器上的csv文件

问题描述:

I am trying to export a MySQL query result to a remote ftp server.

I have the below code but I am currently getting an error:

Warning: ftp_put() [function.ftp-put]: Opening ASCII mode data connection. in /home/hulamyxr/public_html/kisv2/xmltest/export.php on line 50

I would think that my $file = $csv_filename; might be the issue as this is fetching the csv file that has just been created on my local server?

any ideas?

My syntax is:

<?php
$host = 'localhost';
$user = 'un';
$pass = 'pwd';
$db = 'dbname';
$table = 'v2ReportingTable';
$file = 'export';
$datetime=date("Y-m-d H:i:s");
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());

//Create a CSV for 
$result = mysql_query("SELECT * FROM dbname.v2ReportingTable"); 
if (!$result) die('Couldn\'t fetch records'); 
$num_fields = mysql_num_fields($result); 
$headers = array(); 
for ($i = 0; $i < $num_fields; $i++) 
{     
       $headers[] = mysql_field_name($result , $i); 
} 
$csv_filename = "export-" .$datetime.".csv";
$fp = fopen($csv_filename, 'w+');


if ($fp && $result) 
{
    fputcsv($fp, $headers);
    while ($row = mysql_fetch_row($result)) 
    {
        fputcsv($fp, array_values($row)); 
    }
}

//works till here

$ftp_server = "ftp.server.co.za";
$ftp_user_name = "un";
$ftp_user_pass = "pw";
$file = $csv_filename;
$remote_file = "/LocExports/".$file;


// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
 echo "successfully uploaded $file
";
} else {
 echo "There was a problem while uploading $file
";
}

// close the connection
ftp_close($conn_id);
?>

Thanks Again

and it creates the file in the correct location but is a 0kb file and all FTP commands thereafter fail. It is likely that the client is behind a firewall. To rectify this use:

<?php

ftp_pasv($resource, true);

?>