2

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?

1
  • 1
    If the query fails, you die, which ends the program, so there's no point in checking $result later on when it can't possibly be false. You also die after your loop ending the program before you close the file pointer. Why? Commented Feb 14, 2011 at 15:40

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much for this answer. I was experiencing the issue described in this post, and your answer perfectly fixed the issue I was facing. Thank you!
1

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.

Comments

0

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.