-1

Here my php script to export database info to CSV file.

I dont arrive to put any structure to correctly tidy my infos in my CSV file.

For example, put all names in a name column, all emails in an email column... etc

include_once('conf.php');
include_once('BDD.php');

header('charset=UTF-8');
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");


$bdd = new BDD($conf['bddhost'], $conf['bddport'], $conf['bddname'], $conf['bdduser'], $conf['bddpass']);
$sql = "SELECT * FROM user";
$qry = $bdd->prepare($sql);

// Execute the statement
$qry->execute();

$data = fopen('/tmp/db_user_export_".time().".csv', 'w');


while ($row = $qry->fetch(PDO::FETCH_ASSOC))
{
    // Export every row to a file
    fputcsv($data, $row);
    echo ''.$row['prenom'].' '
                .$row['nom'].' '
                .$row['email'].' '
                .$row['cp'].' '
                .$row['information'].'  
                ';
}
fclose($data);
colinec
  • 31
  • 6
  • What is your question? I realize there's a language barrier, but it's difficult to understand what you're asking or how your code doesn't work. – David Oct 09 '14 at 15:38
  • `CSV - "comma separated values"`...where's your commas? Where's your quotes? WHat is the question? – charlietfl Oct 09 '14 at 15:38
  • you may want to activate errors (`error_reporting(E_ALL);ini_set('display_errors', 'On');`) and check the output of `fputcsv` which should return the length of the string written. Maybe try to remove `header()`s functions to help debugging. Maybe it's a write permission on /tmp – Asenar Oct 09 '14 at 15:39

2 Answers2

0

You don't want to use echo as you are creating the file with fputcsv

while ($row = $qry->fetch(PDO::FETCH_ASSOC))
{
    // Export every row to a file
    fputcsv($data, $row);
}

// reset the file pointer to the beginning of the file
rewind($data);

// dump the csv file and stop the script
fpassthru($data);
exit;
cmorrissey
  • 8,493
  • 2
  • 23
  • 27
0

Syntax errors:

$data = fopen('/tmp/db_user_export_".time().".csv', 'w');
              ^--                  ^--      ^--  ^---

You're mixing string quoting styles, so your filename is literally going to contain the characters ", ., t, etc... in it.

Try

$data = fopen('/tmp/db_user_export_' .time() .'.csv', 'w');
                                   ^----------^---

instead. Note the change from " -> '.

Marc B
  • 356,200
  • 43
  • 426
  • 500