I'm using this fputcsv co开发者_开发百科de:
$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?
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
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.
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:
- Use
mysql_fetch_assoc()
- Or:
mysql_fetch_array($result, MYSQL_ASSOC)
精彩评论