How to print function result, if worked print -- yes, else ERROR
I am writing a small data entry form. Data gets entered in html form by user & then into csv file on server. Consider the following snippet, that i wrote to do this
if(!empty($_POST)) {
$handler = fopen('database.csv','a') or exit("Error: Unable to open file!");
fputcsv($handler,$_POST);
fclose($handler);
}
?>
Pretty simple!
The only "fancy" task is display a message to confirm that the entry has been added to the database(Entry added), clearing the form ready for the next entry. Or incase of error, display error message(Doh! Write failed ). I can use OR statement but that would only be invoked incase of an error.
Any idea how to do this?
[UPdate] Th开发者_JAVA百科anks for excellent replies everyone! I added conditional statement as everyone suggested
if(!empty($_POST)) {
$handler = fopen('database.csv','a') or exit("Error: Unable to open file!");
if(fputcsv($handler,$_POST)) {
echo 'everything okay, add next record';
}
else {
exit('Error: Record add failed. Try again or contact admin');
}
fclose($handler);
}
if(!empty($_POST)) {
$handler = fopen('database.csv','a');
if ($handler === FALSE) {
exit("Error: Unable to open file!");
} else {
fputcsv($handler,$_POST);
fclose($handler);
echo "everything A-ok";
}
}
You can include a 3-state switch that:
) does data entry and re-displays the cleared form;
) displays the error and re-populates the form so user can fix it;
) default to no data entry, clear form
Use a post or session variable to specify the action to take, default to no action if the variable is not set or does not validate.
精彩评论