Skip to content Skip to sidebar Skip to footer

Why Is Fputcsv Producing Duplicate Columns?

I am adding a download button to a WordPress site that will query our database, and offer up the result as a CSV. Everything works, except the CSV produced has a duplicate column

Solution 1:

The PDO method fetchAll() has a parameter fetch_style which as documented will return an array with both numerical and named associative keys causing you to have duplicates when you iterate over the array.

You can set it using one of the PDO Fetch constants documented here - they all start with PDO::FETCH_ and use that to get either an associative array (PDO::FETCH_ASSOC) or a numerical array (PDO::FETCH_NUM)

return$statement->fetchAll(PDO::FETCH_ASSOC);

Solution 2:

This works in MSSQL to prevent duplicate columns:

while ( $row = mssql_fetch_array($results, MSSQL_ASSOC) ) {
    fputcsv($fp, $row);     
}

Post a Comment for "Why Is Fputcsv Producing Duplicate Columns?"