-3

I have a problem with putting data from mysql database to csv file. The column headers are ok but rest of rows from table are in one column. Please help..

<?php
$con=mysqli_connect("localhost","asasdd","asasdasd","asdasd");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename=data.csv');
  $output = fopen('php://output', 'w');

  $array = array("Id;Imie_i_nazwisko;Nazwa_kursu;Data_kursu");
  $array = str_replace('"', '', $array);
  fputcsv($output, $array);

  $rows = mysqli_query($con, 'SELECT * FROM kursanci');
  while ($row = mysqli_fetch_assoc($rows))
  {
    fputcsv($output, $row);
  }
  mysqli_close($con);

?>

Resolved should be like this:

<?php
$con=mysqli_connect("localhost","asd","asd","asd");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename=data.csv');

  $output = fopen('php://output', 'w');
  $array = array('Id','Imie_i_nazwisko','Nazwa_kursu','Data_kursu');
  fputcsv($output, $array, ';');

  $rows = mysqli_query($con, 'SELECT * FROM kursanci');
  while ($row = mysqli_fetch_assoc($rows))
  {
    fputcsv($output, $row, ';');
  }
  mysqli_close($con);

?>

Kermit
  • 49
  • 1
  • 8
  • 1
    `$array = array("Id;Imie_i_nazwisko;Nazwa_kursu;Data_kursu")` The array contains a single string value..... what's with the `;` ? Are you trying to set `;` as the separator.... use fputcsv() properly – Mark Baker May 19 '16 at 19:10
  • What's up with this nonsense -> `$array = array("Id;Imie_i_nazwisko;Nazwa_kursu;Data_kursu"); $array = str_replace('"', '', $array);`? Just build an array directly like `$array = array("Id", "Imie_i_nazwisko", "Nazwa_kursu", "Data_kursu")`. – Mike Brant May 19 '16 at 19:14
  • Hard to know without seeing an example of the data in the database. What does a sample `var_dump($row)` look like? You should fetch a numerically-indexed array from the DB result set, not an associative array. – Mike Brant May 19 '16 at 19:16
  • array(4) { ["id"]=> string(1) "3" ["imie_i_nazwisko"]=> string(20) "Zenkowski ZdzisĹaw " ["nazwa_kursu"]=> string(6) "Kurs 3" ["data_kursu"]=> string(10) "2016.05.12" } – Kermit May 19 '16 at 19:54

1 Answers1

0

CSV files expects "," as separator. Only MS-Excel uses ";" as separator by default.

Replace ; for ,, make your array with multiples elements for your header and be happy!

$array = array("Id;Imie_i_nazwisko;Nazwa_kursu;Data_kursu");
$array = array('Id','Imie_i_nazwisko','Nazwa_kursu','Data_kursu');

If you are using MS-Excel and/or need to use ";" as separator, just use this:

$array = array('Id','Imie_i_nazwisko','Nazwa_kursu','Data_kursu');
fputcsv($output, $array, ';');
....
fputcsv($output, $row, ';');
....
Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29