views:

113

answers:

3

This code exports data into a csv file, which is opened within Excel.

When a string has a comma within it, it messes up the order of the data.

I need help modifying my code below to resolve any strings that contain a comma within it, to not to create a new column until after the string.

I am assuming it will pass each string within double quotes or something that contains the string, so any comma within those quotes, then it will make an exception.

Any help is appreciated.

$result = mysql_query("select lname, fname, email, dtelephone, etelephone, contactwhen, comments, thursday, 
friday, saturday, sunday, monday FROM volunteers_2010");

$csv_output .= "Last Name,First Name,Email,Telephone (Day),Telephone (Evening),Contact When,Comments,Thursday,Friday,Saturday,Sunday,Monday,Comments\n";

$i = 0;
if (mysql_num_rows($result) > 0) {
 while ($row = mysql_fetch_assoc($result)) {
  $csv_output .= $row['Field'].", ";
  $i++;
 }
}
$csv_output .= "\n";

$values = mysql_query("SELECT lname, fname, email, dtelephone, etelephone, contactwhen, comments, thursday, 
friday, saturday, sunday, monday FROM volunteers_2010 WHERE venue_id = $venue_id");

while ($rowr = mysql_fetch_row($values)) {
 for ($j=0;$j<$i;$j++) {
  $csv_output .= $rowr[$j].", ";
 }
 $csv_output .= "\n";
}
+3  A: 

fputcsv()

Ignacio Vazquez-Abrams
+1 - Don't re-invent the wheel, csv is a well defined format that has many correct implementations.
R0MANARMY
No, it's not "well defined" as various applications vary in their format, but there are a couple of common patterns which most CSV programs adhere to :-) One example of inconsistency is Microsoft Excel which, at least with Swedish locale, use semi-colon to separate the fields (!). Still +1 for not reinventing the wheel though.
Emil Vikström
so it should look something like: fputcsv(split(',',$row['Field'])); and fputcsv(split(',',$rowr[$j]));
Brad
+3  A: 

see article in wikipedia

Fields with embedded commas must be enclosed within double-quote characters

renick
A: 

Correct format: "test", "test,", "use double "" quotes inside"

1st loop:

$csv_output .= '"' . str_replace('"', '""', $rowr['Field']) . '", ';

2nd loop:

$csv_output .= '"' . str_replace('"', '""', $rowr[$j]) . '", ';
frame