I have a form that when submits, writes the data to a text file. This all work properly. However, if the form data is submitted successfully, I would like to display a success message to the user to let him/her know.
I understand that if (isset($_POST['submit'])) {... will only run if the Submit button is clicked. This is where my success message should be written and is where I have it in the code below. I don't understand though why my success message is displaying each time the page loads even though the submit button is not clicked!
Can someone help me please. Thanks in advance.
<html>
<head></head>
<body>
<form name="input" method="post"
action="<?php echo $_SERVER['SCRIPT_NAME']?>">
<b>Movie 1:</b><br><br>
<p><label for="title1">Title: </label>
<input type="text" size="60" name="title1" id="title1" /></p>
<p><label for="actors1">Main Actors: </label>
<input type="text" size="70" name="actors1" id="actors1" /></p>
<p><b>Movie 1 Description:</b><br>
<textarea rows="10" cols="80" name="description1"></textarea></p>
<br>
<hr>
<b>Movie 2:</b><br><br>
<p><label for="title2">Title: </label>
<input type="text" size="60" name="title2" id="title2" /></p>
<p><label for="actors2">Main Actors: </label>
<input type="text" size="70" name="actors2" id="actors2" /></p>
<p><b>Movie 2 Description:</b><br>
<textarea rows="10" cols="80" name="description2"></textarea></p>
<br>
<hr>
<p><input type="reset" name="reset" value="reset" />
<input type="submit" name="submit" value="Save Changes" /></p>
</form>
<!--On submit, write to file-->
<?php
if (isset($_POST['submit'])) {
$title1 = $_POST['title1'];
$title1 = "\$title1=\"" . $title1 . '";';
$actors1 = $_POST['actors1'];
$description1 = $_POST['description1'];
$title2 = $_POST['title2'];
$actors2 = $_POST['actors2'];
$description2 = $_POST['description2'];
$fp = fopen("db/data.txt","w");
if(!$fp) {
echo 'Error, the file could not be opened or there was an error creating it.';
exit;
}
fwrite($fp, $title1."\n" . $actors1. "\n" . $description1. "\n" . $title2."\n" . $actors2. "\n" .
$description2. "\n");
fclose($fp);
}
echo 'Your data was saved successfully!';
//This text shows as soon as page loads instead of when the submit button is clicked.
?>
<!--End submit-->
</html>