0

I tried to generate a .csv file, but I get this file empty. So my code is :

$fileName = 'Users_' . date('d-m-Y') . '.csv';
$fh = fopen($fileName, "w");
fputcsv($fh, array('EMAIL', 'NAME','SURNAME'), ";");
foreach ($aDataBases as $database) {
    $sSql = sprintf('SELECT email, name, surname FROM users');
    $rResult = Mysqli::query($sSql, $database);
    while ($aRecord = $rResult->fetch_array(MYSQLI_ASSOC)){
       fputcsv($fh, $aRecord['email'], ";");
       fputcsv($fh, $aRecord['name'], ";");
       fputcsv($fh, $aRecord['surname'], ";",'"');
    }
}
fclose($fh);

The file is generate but is empty, can you help me please ? I make a print_r() and there are data after query execution. What I'm doing wrong ?

Harea Costicla
  • 797
  • 3
  • 9
  • 20

3 Answers3

3

You have to change this lines to

while ($aRecord = $rResult->fetch_array(MYSQLI_ASSOC)){
    fputcsv($fh, $aRecord['email'], ";");
    fputcsv($fh, $aRecord['name'], ";");
    fputcsv($fh, $aRecord['surname'], ";",'"');
}

to

while ($aRecord = $rResult->fetch_array(MYSQLI_ASSOC)){
    fputcsv($fh, [$aRecord['email'], $aRecord['name'], $aRecord['surname']]);
}

Check here http://php.net/manual/en/function.fputcsv.php#refsect1-function.fputcsv-parameters second parameter should be an array which you were missing

ARIF MAHMUD RANA
  • 5,026
  • 3
  • 31
  • 58
1

Second parameter to fputcsv should be an array, but in your code sample it's a string.

Keilo
  • 963
  • 1
  • 7
  • 13
0

The second parameter of fputcsv is an array.

You could do it like this:

$fields = [];

while ($aRecord = $rResult->fetch_array(MYSQLI_ASSOC)){
    $fields[] = $aRecord['email'];
    $fields[] = $aRecord['name'];
    $fields[] = $aRecord['surname'];

    fputcsv($fh, $fields);
}
Allan
  • 273
  • 1
  • 8