gpt4 book ai didi

php将带有动态列的mysql数据导出到csv

转载 作者:行者123 更新时间:2023-11-29 18:34:40 25 4
gpt4 key购买 nike

iam 是 php 新手,我知道如何将静态列的 mysql 结果导出到 csv,但在某些情况下,我必须动态导出而不指定列名称。我已经在下面尝试过了,我需要帮助才能完成这项工作。

PHP

<?php
if(isset($_POST['action']) && $_POST['action'] == 'test_export_to_csv'){


$head_qry = mysql_query("SELECT `header_display_name` FROM expense_heading WHERE expense_id='$expense_id' order by col_order");

$columnValues = Array();

while ( $row = mysql_fetch_assoc($head_qry) ) {

$columnValues[] = $row['columnname'];

}
$filename = "uploads/reports/".$invoice_id.".csv";
$file = fopen($filename, 'w+');

fputcsv($file,$columnValues);

$data_qry="SELECT $columnValues from invoice_detail where invoice_id='$invoice_id'";

$data_result=mysql_query($data_qry);
while($result=mysql_fetch_assoc($data_result)){
$report_array=array($result[$columnValues]);
fputcsv($file, $report_array);
}
fclose($file);

if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');


header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");

// change, added quotes to allow spaces in filenames
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();
}

最佳答案

我想这样的事情应该有效:

$columnValues = Array();

while ( $row = mysql_fetch_assoc($head_qry) ) {
$columnValues[] = $row['columnname'];
}
$filename = "uploads/reports/".$invoice_id.".csv";
$file = fopen($filename, 'w+');

fputcsv($file,$columnValues);

// don't use `array_keys`
$columnValuesStr = implode(', ', $columnValues);

$data_qry = "SELECT $columnValuesStr from invoice_detail where invoice_id='$invoice_id'";

$data_result = mysql_query($data_qry);
while ($result = mysql_fetch_assoc($data_result)) {
// `$result` already an array which holds values of selected fields,
// you can pass it directly to `fputcsv`
fputcsv($file, $result);
}

关于php将带有动态列的mysql数据导出到csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45398983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com