使用php pdo将数据从db插入到csv文件中

时间:2018-06-19 09:19:08

标签: php sql pdo export-to-csv fgetcsv

我正在尝试将从数据库中选择的数据插入到csv文件中。我被困在这里,不知道为什么它不起作用。它让我给出这样一个文件: enter image description here

由于某种原因,它将列名放入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);      
}
?>

有谁知道我做错了什么?

1 个答案:

答案 0 :(得分:0)

检查以下代码并注意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 '$date1' AND '$date2'";    
$query = $conn->prepare($sql); 
while($row = $query->fetch(PDO::FETCH_ASSOC))  
{  
fputcsv($output, $row);  
}  
fclose($output);      
}
?>