help with PHP to csv

I have a HTML code that opens a simple web form where a user can nominate another member of staff to be entered into a prize draw, which is working lovely…

My question is that I’m trying to create a PHP script that will write a csv of all the data that is entered, so we can then export this into Excel.

So far I have “data.csv” and “write_to_csv.php” in the same folder, can anyone have a look at my code and see where I’m going wrong?

[code]

<?php // Contact From $fromstaff = $_POST['from']; // Contact Student Name $staffname = $_POST['staffname']; // Contact Issue $reason = $_POST['reason']; //Mail To $to = '[email protected]'; //Mail Subject $subject = 'Give Thanks'; //Mail Message $message = "

GiveThanks Form

From
$fromstaff

Staff Name
$staffname

Reason
$reason

"; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'To: Charlie ' . "\r\n"; $headers .= 'From: Give Thanks ' . "\r\n"; $send_contact=mail($to,$subject,$message,$headers); if($send_contact){ echo " We've received your Give Thanks! Your nominee will now be entered into the draw "; } else { echo "ERROR"; } $fp = fopen ("/w2k8r2app1/D$/inetpub/GiveThanksTest/data.csv", "a+"); fwrite ($fp, "," . $_POST['from'] . "," . $_POST['staffname'] . "," . $_POST['reason'] . "," . "\a+"); fclose ($fp); ?> [/CODE]

Try this.
[php]

<?php $file = "/w2k8r2app1/D$/inetpub/GiveThanksTest/data.csv"; if($fp = fopen("$file", 'ab')) { flock($fp, LOCK_EX); // lock the file so no-one else can write to it. fwrite($fp, $fromstaff . ","); // add the data to the logfile. fwrite($fp, $staffname . ","); fwrite($fp, $reason . "\r\n"); // add new line here.. flock($fp, LOCK_UN); // unlock the file! fclose($fp); // close the file } ?>

[/php]

Red :wink:

Not working I’m afraid Redscouse :frowning: just out of interest, why the “f lock”? Do I need to lock the file and then open it?

Thanks

If two requests hit at the same time (or while the file is open) you can get some interesting results if the file stays open. With a lock the 2. (3. and 4. etc) process will have to wait until the first one is finished with the file.

What Jim said…

Thanks Jim :wink:

If the file is not writing, i would assume the path is incorrect, is it?

$file = ‘/w2k8r2app1/D$/inetpub/GiveThanksTest/data.csv’;

Edit: Or perhaps you may need to change the permissions of the file being written to, might want to check that out also…

Sponsor our Newsletter | Privacy Policy | Terms of Service