在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列?
最佳答案
根据您当前的代码:
$connection = connectToDB();
$query = "SELECT id,col1 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] = calX($row[0]);
$csvrow[3] = calY($row[1]);
fputcsv($fp, array_values($csvrow));
}
die;
}
我编辑的代码也可以进一步优化。
关于php - 计算值并从MySQL导出到csv,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41905494/