PHP fputcsv输出双记录

PHP fputcsv输出双记录

问题描述:

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?

我正在使用此fputcsv代码: p>

  $ result  = mysql_query('SELECT * FROM`mash`'); 
if(!$ result)die('couldn \ ttt tetch records'); 
 $ fp = fopen('testCSV.csv','w');  
if($ fp&& $ result){
 while($ row = mysql_fetch_array($ result)){
 fputcsv($ fp,array_values($ row)); 
} 
 die; 
  } 
 nclclose($ fp); 
  code>  pre> 
 
 

它输出的CSV很棒,但每个mysql列有两列(所以一切都加倍) p> \ n

谁能明白为什么会这样? p> div>

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

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:

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.