Html Form Not Outputting To Csv File (or Displaying Correct Error Messages)
I'm having trouble creating a form that exports to a .CSV file in PHP. I created a fiddle for the HTML which is here: http://jsfiddle.net/tqs6g/ I'm coding in PHP so I can't really
Solution 1:
<?phpif ($_SERVER['REQUEST_METHOD'] == 'POST') { // better method to check for a POSt
... validation stuff ...
$data = array();
$data[] = $_POST['brandname'];
$data[] = $_POST['firstname'];
etc...
if (empty($errrorMessage)) {
$fs = fopen('mydata.csv', 'a') ordie("Unable to open file for output");
fputcsv($fs, $data) ordie("Unable to write to file");
fclose($fs);
exit();
} else {
echo$errormessage;
}
}
A few things of note:
1) using $_SERVER['REQUEST_METHOD'] to check for submit type is absolutely reliable - that value is always set, and will always be POST if a post is being performed. Checking for a particular form field (e.g. the submit button) is hacky and unreliable.
2) Using fputcsv() to write out to a csv file. PHP will do all the heavy work for you and you jus tprovide the function an array of data to write
3) Note the or die(...)
constructs, which check for failures to open/write to the file. Assuming that a file is available/writeable is unreliable and will bite you at some point in the future. When dealing with "external" resources, always have error handling.
Post a Comment for "Html Form Not Outputting To Csv File (or Displaying Correct Error Messages)"