fputcsv is putting duplicate values in my file

Mithrand1r

I have read all topics about problem which was described at stackoverflow linked to problem of duplicated values in fputcsv function. Unfortunately I am using PDO and psql (presented solutions was described using simple mysql connectors)

But first I will describe my problem showing some code. Here is what I put:

$db=ConnectionFactory::CreateConnection();

$fileName = 'somefile.csv';

header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$fileName}");
header("Expires: 0");
header("Pragma: public");


    $fh = @fopen( 'php://output', 'w' );


    $query = "SELECT * FROM person";
    $results = $db->query($q)->fetchall();

    $headerDisplayed = false;

    foreach ( $results as $data ) {
        // Add a header row if it hasn't been added yet
        if ( !$headerDisplayed ) {
            // Use the keys from $data as the titles
            fputcsv($fh, array_keys($data));
            $headerDisplayed = true;
        }

        // Put the data into the stream
        fputcsv($fh, $data);
    }
    // Close the file
    fclose($fh);
    // Make sure nothing else is sent, our file is done
    exit;

CSV file I am getting contains double values, for example:

"name","name","phone","phone","email","email"
"John","John","501231","501231","test","test"
"Bob","Bob","1111","1111","test2","test2"

When I am trying to execute function pg_fetch_array I am getting error:

pg_fetch_array() expect parameter 1 to be resource, array given

What can I do to fix my csv?

Mark Baker

Default for a PDO fetch() or fetchall() is PDO::ATTR_DEFAULT_FETCH_MODE, which is to retrieve the row as both enumerated and associative array, so you will get duplication

Fetch as either enumerated, or as associative, but don't simply default it

$db->query($q)->fetchall(PDO::FETCH_ASSOC);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related