Reputation: 311
I'm trying to insert data that I select from my database into a csv file. I got stuck here and don't know why it doesn't work. It keeps me giving a file like this:
For some reason it put the column names into 1 field (A1) I'm using this code now:
<?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);
}
?>
Does anyone know what I'm doing wrong?
Upvotes: 1
Views: 1055
Reputation: 450
Check below code and notice change in SQL statement. Also need to do data sanitization to prevent SQL injection,
<?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);
}
Upvotes: 1