Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.