Search code examples
phpmysqlcsvfputcsv

PHP fputcsv outputting double records


I'm using this fputcsv code:

$result = mysql_query('SELECT * FROM `mash`');
if (!$result) die('Couldn\'t fetch records');
$fp = fopen('testCSV.csv', 'w');
if ($fp && $result) {
    while ($row = mysql_fetch_array($result)) {
        fputcsv($fp, array_values($row));
    }
    die;
}
fclose($fp);

It outputs the CSV great but there are two columns for each mysql column (so everything is doubled)

could anyone see why that would be?


Solution

  • try this:

    $result = mysql_query('SELECT * FROM `mash`');
    if (!$result) die('Couldn\'t fetch records');
    $fp = fopen('testCSV.csv', 'w');
    if ($fp && $result) {
        while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
            fputcsv($fp, array_values($row));
        }
        die;
    }
    fclose($fp);
    

    mysql_fetch_array will return a combined array by default, this will return associative array only. Or use MYSQL_NUM for numbered - http://php.net/manual/en/function.mysql-fetch-array.php