计算值并从MySQL导出到csv

时间:2017-01-28 01:25:52

标签: php mysql csv

在MySQL中我必须遵循表

 ID     col1    
 1      234
 2      987
 3      544

我想使用Php将此数据导出到.csv文件,如下所示

ID     col1    x     y
1      234   9891   18762
2      987   8763   37269
3      544   1852   86329

其中x和y中的值是使用col1

中的值的2个函数的结果
function calX (col1){

}

function calY (col1){

}

从这里的帖子我得到以下代码:

$connection = connectToDB();

$query = "SELECT * FROM mytable";

$result = $connection->query($query);

if (!$result) die('Couldn\'t fetch records');

$headers = $result->fetch_fields();

foreach ($headers as $header) {
     $head[] = $header->name;
}
$fp = fopen('php://output', 'w');

if ($fp && $result) {
   header('Content-Type: text/csv');
   header('Content-Disposition: attachment; filename="export.csv"');
   header('Pragma: no-cache');
   header('Expires: 0');
   fputcsv($fp, array_values($head));
   while ($row = $result->fetch_array(MYSQLI_NUM)) {
       fputcsv($fp, array_values($row));
   }
   die;
}

如何添加x和y列?

3 个答案:

答案 0 :(得分:1)

根据您当前的代码:

md
$S$: a set of shops
$I$: a set of items M wants to get

我编辑的代码也可以进一步优化。

答案 1 :(得分:0)

说两个函数都计算并返回x和y值。我正在重写你的代码

$connection = connectToDB();
$query = "SELECT * FROM mytable";
$result = $connection->query($query);
if (!$result) die('Couldn\'t fetch records');
$headers = $result->fetch_fields();
$i=0;
foreach ($headers as $header) {
    $head[$i++] = $header->name;
}
$head[$i++]="x";
$head[$i]="y";
$csvrow = array();
$fp = fopen('php://output', 'w');
if ($fp && $result) {
   header('Content-Type: text/csv');
   header('Content-Disposition: attachment; filename="export.csv"');
   header('Pragma: no-cache');
   header('Expires: 0');
   fputcsv($fp, array_values($head));
   while ($row = $result->fetch_array(MYSQLI_NUM)) {
       //if there are more elements in row better do loop 
       $csvrow[0] = $row[0];
       $csvrow[1] = $row[1];
       $csvrow[2] = functionCalX($row[1]); 
       //add Y also , also do typechecking if needed
       fputcsv($fp, array_values($csvrow));
   }
   die;
}

我编辑了相同的代码,它可以进行优化。我不熟悉php

答案 2 :(得分:0)

没有看到功能就很难说 $ sumxy = $ x + $ y;

echo $ sumxy;

这里也是csv导出文档的链接 http://php.net/manual/en/function.fputcsv.php