使用PHP添加新列并将总计添加到可下载的CSV文件中

时间:2014-05-27 08:08:04

标签: php mysql csv

用户可以通过点击“下载CSV文件”下载发票。发票从我的数据库中提取以下数据:

$sql = mysql_query("SELECT Jobs.date, Jobs.order_ref, Jobs.quantity, Jobs.packing_price, Jobs.dispatch_type, Jobs.courier_price from Jobs WHERE order_type = 'Retail' AND confirmed = 'Yes'");

我正在尝试向文件“total”和“subtotal”添加2个新列,这些列将包含行总计,然后是总计。我的代码不会添加新列,也不会计算总计。我得到一个0.

<?php
include("../controllers/cn.php");

// Fetch record from Database
$output= "";

$sql = mysql_query("SELECT Jobs.date, Jobs.order_ref, Jobs.quantity, Jobs.packing_price, Jobs.dispatch_type, Jobs.courier_price from Jobs WHERE order_type = 'Retail' AND confirmed = 'Yes'");

$columns_total = mysql_num_fields($sql);

// Get The Field Name

/********************************
 *      RETAIL
 ********************************/
for ($i = 0; $i < $columns_total; $i++) {
    $heading = mysql_field_name($sql, $i);

    $output .= '"'.$heading.'",';
}
$output .="\n";

while ($row = mysql_fetch_array($sql)) {

    $data[] = 'New Column';
    $newCsvData[] = $data;
    for ($i = 0; $i < $columns_total; $i++) {
        $total[] .= $i['packing_price'] + $i['courier_price'];
        $sum .= $['packing_price'] + $i['courier_price']; 
        $output .='"'.$row["$i"].'",';
    }
    $output .="\n";
}

// Download the file
$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

echo "Retail";
echo "\n";
echo $output;

?>

1 个答案:

答案 0 :(得分:0)

$sum = 0;
while ($row = mysql_fetch_array($sql)) {
    for ($i = 0; $i < $columns_total; $i++) {
        $output .='"'.$row["$i"].'",';
    }
    $total = $row['packing_price'] + $row['courier_price'];
    $output .= $total;
    $sum += $total; // Add to overall total
    $output .="\n";
}
// Download the file
$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

echo "Retail";
echo "\n";
echo $output;
echo "$sum\n";