Page 1 of 1

How to solve problem with saving query result to CSV file?

Posted: Tue May 25, 2004 12:59 pm
by ljCharlie
I have a SELECT statement that will query MySQL database and then fwrite() to a .CSV file for download. To save as a CSV file, I have to put in some comas before fwrite() into the file. The problem is that many of the data strings in the database also contain comas. So when I open the CSV file in Excel, the data is not line up because of the extra comans that are already in the database with the strings. Is there a way to solve this problem or prevent this problem when fwrite() to a .csv file?

Any suggestion is much appreciated.

ljCharlie

Posted: Tue May 25, 2004 1:03 pm
by magicrobotmonkey
put the data in quotes!

Posted: Tue May 25, 2004 1:14 pm
by ljCharlie
Many thanks for the quick response. Here's what I have.

Code: Select all

$dataContent = "".$rowї'LstName'].",".$rowї'MdnName'].",".$rowї'FstName'].",".$rowї'MdlName'].",".$rowї'NckName'].",".$rowї'FstMajor'].",".$rowї'FstYear'].",".$rowї'FstDegree'].",".$rowї'SndMajor'].",".$rowї'SndYear'].",".$rowї'SndDegree'].",".$rowї'Email'].",".$rowї'Website'].",".$regDate."\n";
But this doesn't work, like I said, the data in the database field contains a coma.

One other option is to save as tab delimited. However, I don't know what the php code for inserting a tab. Help on this issue is also welcome.

ljCharlie

Posted: Tue May 25, 2004 1:17 pm
by magicrobotmonkey
like this

Code: Select all

$dataContent = """.$rowї'LstName']."","".$rowї'MdnName']."", etc..
\" escapes the quote so it ends up like

"var","var2",
and excel will treat it like one big string, ignoring the commas

Posted: Tue May 25, 2004 1:18 pm
by Weirdan
ljCharlie wrote:Many thanks for the quick response. Here's what I have.

Code: Select all

$dataContent = "".$rowї'LstName'].",".$rowї'MdnName'].",".$rowї'FstName'].",".$rowї'MdlName'].",".$rowї'NckName'].",".$rowї'FstMajor'].",".$rowї'FstYear'].",".$rowї'FstDegree'].",".$rowї'SndMajor'].",".$rowї'SndYear'].",".$rowї'SndDegree'].",".$rowї'Email'].",".$rowї'Website'].",".$regDate."\n";
hm.... you can try:

Code: Select all

$dataContent = '"' . implode('","', $row) . '"';
ljCharlie wrote: One other option is to save as tab delimited. However, I don't know what the php code for inserting a tab. Help on this issue is also welcome.
Tabs are denoted as \t in double quoted strings

Posted: Tue May 25, 2004 1:35 pm
by ljCharlie
Genius! The \" works like a charm. I'll test the implode and see if that works too. In the mean time, many thanks to both of you for helping me out.

ljCharlie