我试图让用户能够在我的服务器上下载他们所有数据的 CSV 备份。这意味着我正在尝试执行多个查询并将结果放入 CSV 文件中。
这是我到目前为止所拥有的:
<?php
// Connect
include 'config.php'; // Config contains PDO database connection, etc.
// Generate filename
$filename = $_SESSION['current_group'].'-'.date('d.m.Y').'.csv';
// Get backup data from MYSQL database
$result_users = $conn->prepare('SELECT `user_name`, `user_email` FROM `users` WHERE `group_id` = ?');
$result_users->execute(array($_SESSION['current_group_id']));
$result_items = $conn->prepare('SELECT `item_name`, `item_value`, `item_group` FROM `items` WHERE `group_id` = ?');
$result_items->execute(array($_SESSION['current_group_id']));
# Create array
$list = array ("## START OF USER TABLE ##");
// Append results to array
while ($row = $result_users->fetch(PDO::FETCH_ASSOC)) {
array_push($list, array_values($row));
}
array_push($list,"## END OF USER TABLE ##");
array_push($list,"## START OF ITEMS TABLE ##");
while ($row = $result_items->fetch(PDO::FETCH_ASSOC)) {
array_push($list, array_values($row));
}
array_push($list,"## END OF ITEMS TABLE ##");
// Output array into CSV file
$fp = fopen('php://output', 'w');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$filename.'"');
foreach ($list as $ferow) {
fputcsv($fp, split(',',$ferow));
}
?>
预期的输出应该是这样的:
## START OF USERS TABLE ##
"John","john@email.com"
"James","james@email.com"
## END OF USERS TABLE ##
## START OF ITEMS TABLE ##
"Soap","A lot","Household"
"Banana","2","Food"
## END OF ITEMS TABLE ##
等等
问题是 value 没有正确地推入 $list 数组。我应该怎么做才能得到想要的结果?
谢谢!