使用foreach函数将CSV导出到文件夹

I have an php script, which i want to use to automatically export data from a certain mysql table, to a CSV file in a directory. The script is working fine and the files are saved in the right directory, but u want, that every order, exports to a separate CSV file.

Like:

  • 12-09-2016-05-21_csvexport_1.CSV < data from order 1
  • 12-09-2016-05-21_csvexport_2.CSV < data from order 2
  • And so on..

I want to run the script automatically with a cronjob. The orders to be exported as a separate csv file, can be selected with a date range. Like only create csv files from the last 2 days. It doesn't matter if the CSV files are going to overwrite. The order table looks like this:

id_order    date        customer
1       01-01-2016  1223
2       01-02-2016  1224
3       01-03-2016  1225
4       01-04-2016  1226
5       01-05-2016  1227

And the php script looks like this:

<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'database';
$table = 'columns';
$file = 'csvexport';
$dir = 'csv';

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

function escape_csv_value($value) { 
$value = str_replace('"', '""', $value);
if ( preg_match( '/\|\
|,|"/', $value ) ) {
return '"' . str_replace( '"', '""', $value ) . '"';
} else { 
return $value;
} 
} 

$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++;
}
}
    
$values = mysql_query("SELECT id_order, date, customer FROM orders");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= escape_csv_value($rowr[$j]).';'; 
}
$csv_output .= "
";
}
    
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: attachment; filename=".$filename.".csv"); 

$filename = date("d-m-Y-i-s_", time()) . $file.".csv";

print $csv_output;
    file_put_contents($dir ."/".$filename, $csv_output);
}
?>

I hope someone can help me. Thanks in advance.

</div>