PHP fputcsv outputting double records

4.2k views Asked by At

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?

3

There are 3 answers

1
Brian On BEST ANSWER

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

0
Aron Rotteveel On

mysql_fetch_array() returns both a numeric and associative index by default:

Quoting the manual (emphasis mine):

Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).

Solution:

0
blongden On

http://php.net/manual/en/function.mysql-fetch-array.php

The second parameter to mysql_fetch_array is the key here. The default is to fetch BOTH the assoc ant int key. You probably want to pass in MYSQL_ASSOC here.