我正在尝试将从数据库中选择的数据插入到 csv 文件中。我被困在这里,不知道为什么它不起作用。它让我不断给出这样的文件:
出于某种原因,它将列名称放入 1 个字段 (A1) 我现在正在使用此代码:
<?php
include "includes/connection.php";
if(isset($_POST['submit'])){
$tabel = $_POST['tabel'];
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="data.csv";');
$output = fopen("php://output", "w");
fputcsv($output, array('Dev_ID', 'Barcode', 'Naam', 'Ip_adres', 'Merk', 'Model', 'CPU', 'Memory', 'Moederbord', 'Serialnummer', 'Aanschaf_dat', 'Aanschaf_waarde', 'Opmerkingen', 'Picture_dev'));
$sql = "SELECT * FROM ".$tabel." WHERE Aanschaf_dat BETWEEN ".$date1." AND ".$date2."";
$query = $conn->prepare($sql);
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
fputcsv($output, $row);
}
fclose($output);
}
?>
有人知道我做错了什么吗?
检查下面的代码并注意 SQL 语句的变化。还需要进行数据清理以防止 SQL 注入,
<?php
include "includes/connection.php";
if (isset($_POST['submit'])) {
$tabel = $_POST['tabel'];
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="data.csv";');
$output = fopen("php://output", "w");
fputcsv($output, array('Dev_ID', 'Barcode', 'Naam', 'Ip_adres', 'Merk', 'Model', 'CPU', 'Memory', 'Moederbord', 'Serialnummer', 'Aanschaf_dat', 'Aanschaf_waarde', 'Opmerkingen', 'Picture_dev'));
$sql = "SELECT * FROM $tabel WHERE Aanschaf_dat BETWEEN ? AND ?";
$query = $conn->prepare($sql);
$query->execute([$date1, $date2]);
foreach ($query as $row) {
fputcsv($output, $row);
}
fclose($output);
}