问题
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 show the full code on JSFiddle since it can't support the PHP but here's my PHP code:
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['brandname']))
{
$errorMessage .= "<li>Please enter a business/brand name.</li>";
}
if(empty($_POST['firstname']))
{
$errorMessage .= "<li>Please enter your first name.</li>";
}
$varBrand = $_POST['brandname'];
$varFName = $_POST['firstname'];
$varLName = $_POST['lastname'];
$varEmail = $_POST['email'];
$varSite = $_POST['website'];
if(empty($errorMessage))
{
$fs = fopen("mydata.csv","a");
fwrite($fs,$varBrand . ", " . $varFName . ", " . $varLName . ", " . $varEmail . ", " . $varSite . "\n");
fclose($fs);
exit;
}
}
?>
When I click Submit it successfully goes to 'thankyou.php' (which is set in the form action) but I can't figure out why it's not posting the correct error messages or filling in my 'mydata.csv' file upon click. Possibly it's a sight syntax error? Let me know if you need any more info, I know this is kind of confusing seeing as the PHP is separated from the Fiddle.
回答1:
<?php
if ($_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') or die("Unable to open file for output");
fputcsv($fs, $data) or die("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.
来源:https://stackoverflow.com/questions/8771486/html-form-not-outputting-to-csv-file-or-displaying-correct-error-messages