【发布时间】:2015-05-24 00:34:08
【问题描述】:
这是我在这个项目上的最后一项任务,我不确定如何根据需要进行调整。我对这一切都很陌生,很高兴我能走到这一步!
以下函数从 3 个表中获取数据并生成一个 CSV 文件(很好并且工作正常),但是它将文件分成 3 个部分,理想情况下,我希望每行每个订单的所有数据。
就目前而言,您可以在 3 个部分中看到 3 个表格,但我确实需要 1 行内的发票 ID 中的所有数据。
代码:
// download invoice csv sheet
if ($action == 'download_csv'){
header("Content-type: text/csv");
// output any connection error
if ($mysqli->connect_error) {
die('Error : ('.$mysqli->connect_errno .') '. $mysqli->connect_error);
}
$tables = array('invoices', 'customers', 'invoice_items'); // array of tables need to export
$file_name = 'invoice-export-'.date('d-m-Y').'.csv'; // file name
$file_path = 'downloads/'.$file_name; // file path
$file = fopen($file_path, "w"); // open a file in write mode
chmod($file_path, 0777); // set the file permission
// loop for tables
foreach($tables as $table) {
$table_column = array();
$query_table_columns = "SHOW COLUMNS FROM $table";
// fetch table field names
if ($result_column = mysqli_query($mysqli, $query_table_columns)) {
while ($column = $result_column->fetch_row()) {
$table_column[] = $column[0];
}
}
// Format array as CSV and write to file pointer
fputcsv($file, $table_column, ",", '"');
$query_table_columns_data = "SELECT * FROM $table";
if ($result_column_data = mysqli_query($mysqli, $query_table_columns_data)) {
// fetch table fields data
while ($column_data = $result_column_data->fetch_row()) {
$table_column_data = array();
foreach($column_data as $data) {
$table_column_data[] = $data;
}
// Format array as CSV and write to file pointer
fputcsv($file, $table_column_data, ",", '"');
}
}
}
//if saving success
if ($result_column_data = mysqli_query($mysqli, $query_table_columns_data)) {
echo json_encode(array(
'status' => 'Success',
'message'=> 'CSV has been generated and is available in the /downloads folder for future reference, you can download by <a href="/downloads/'.$file_name.'">clicking here</a>.'
));
} else {
//if unable to create new record
echo json_encode(array(
'status' => 'Error',
//'message'=> 'There has been an error, please try again.'
'message' => 'There has been an error, please try again.<pre>'.$mysqli->error.'</pre><pre>'.$query.'</pre>'
));
}
// close file pointer
fclose($file);
$mysqli->close();
}
【问题讨论】:
-
这是一个相当大的改变,你要求别人为你做。您需要更改 SQL 查询以连接所有 3 个表并为每个 invoice_item 生成一行。尝试这样做,然后在遇到问题时寻求帮助