Search code examples
phpfputcsv

fputcsv returns double values


So currently i'm trying to make a database exporting script, what I got is this:

<?php
   $con = mysqli_connect("SERVER","USER","PASSWORD","DATABASE");
   $query = mysqli_query($con,"SELECT * FROM `TABLE`;");
   unlink('testfile.csv');
   $fp = fopen("testfile.csv","w");
   fputcsv($fp,array("Col1","Col2","Col3"),";");
   while ($list = mysqli_fetch_array($query)){
     fputcsv($fp,$list,";");
  }
  fclose($fp);
?>

this seems to return "Col1 Col1 Col2 Col2 Col3 Col3"

While fputcsv($fp,array($list[0],$list[1],$list[2]),";"); seems to work fine. Is there a way to avoid this solution and do it by the Original $list array?


Solution

  • Try:

    $list = mysqli_fetch_array($query, MYSQLI_NUM);
    

    This should return the array as a numeric array rather than a mixed map which it defaults to. Try print_r on the output too to make sure it's what you expect.

    https://www.php.net/manual/en/mysqli-result.fetch-array.php