Jump to content

[SOLVED] Help with CSV file and empty fields


tqla

Recommended Posts

Hi. I was hoping someone can help me.

 

I am using this script:

$file = fopen('file.csv', 'w+');
$text = "";
while ($Fields = mysql_fetch_array($result)) {
  $text .= $Fields['FName'] . " ";
  $text .= $Fields['LName'] . ", ";
  $text .= $Fields['CompanyName'] . ", ";
  $text .= $Fields['MAddress'] . " ";
  $text .= $Fields['MAddress2'] . ", ";
  $text .= $Fields['MCity'] . ", ";
  $text .= $Fields['MState'] . " ";
  $text .= $Fields['MZip'] . "\n\r";
}
fwrite($file, $text);
fclose($file);

 

It works fine but the problem is that some of the fields in the database are empty so the resulting Excel file doesn't line up. What I mean is there are last names in the first name column and zip codes in the address column, etc.

 

Is there a way to compensate for empty fields? So that all of the types will line up correctly.

 

Thanks!

I changed it to this just to test it. (there's a comma after each filed) but it still doesn't work!

$file = fopen('file.csv', 'w+');
$text = "";
while ($Fields = mysql_fetch_array($result)) {
  $text .= $Fields['FName'] . ", ";
  $text .= $Fields['LName'] . ", ";
  $text .= $Fields['CompanyName'] . ", ";
  $text .= $Fields['MAddress'] . ", ";
  $text .= $Fields['MAddress2'] . ", ";
  $text .= $Fields['MCity'] . ", ";
  $text .= $Fields['MState'] . ", ";
  $text .= $Fields['MZip'] . ",\n\r";
}
fwrite($file, $text);
fclose($file);

 

MadTechie, I'm confused. How would I integrate your solution into my code?

 

Why don't you just do this:

$file = '/path/to/file/file.csv';
$sql = "SELECT your_statement_here "
       . "INTO OUTFILE '{$file}' "
       . "FIELDS TERMINATED BY ',' "
       . "LINES TERMINATED BY '\n'";
if(mysql_query($sql)){
  // Just a test
  echo file_get_contents($file);
}

 

(EDIT) Never tried this approach, but why do it in PHP when MySQL will do it faster!

Part of programming is using the proper tool for the job.  There's a lot of functionality that you will needlessly write into your PHP programs that can be handled more efficiently by the database, especially things like statistics or date / time functions.

 

So learn both!  Muahahahah

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.