-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);
3
  • 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. Commented Oct 9, 2014 at 15:38
  • CSV - "comma separated values"...where's your commas? Where's your quotes? WHat is the question? Commented Oct 9, 2014 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 Commented Oct 9, 2014 at 15:39

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

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 " -> '.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.