Search code examples
phpcsvexportdata-integrity

Export to csv, string w/ comma in it, splits it up


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";
}

Solution

  • see article in wikipedia

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