benhowdle89
benhowdle89

Reputation: 37464

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?

Upvotes: 2

Views: 4317

Answers (3)

Brian
Brian

Reputation: 8616

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

Upvotes: 7

blongden
blongden

Reputation: 11

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.

Upvotes: 1

Aron Rotteveel
Aron Rotteveel

Reputation: 83173

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:

Upvotes: 0

Related Questions