简体   繁体   中英

Add new column and add totals to downloadable CSV file using PHP

A user is able to download an invoice by clicking the 'download CSV file'. The invoice pulls the following data from my database :

$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'");

I am trying to add 2 new columns to the file "total" and "subtotal" and these will contain the line totals and then the overall total. My code doesn't add a new column and neither does it calculate the totals. I just get a 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;

?>
$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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM