I can write new data to my json file successfully by below coding but it is not displaying the message - File Appended successfully, which is defined in the last bit of my PHP. Please tell me where am I going wrong here ? I does display the error message if the form fields are left empty which is great, but I really want the successful message to be displayed after the data get written, instead, the page starts again from the beginning and I can add a new data then. Thanks in advance.
<?php
/* Declaring two variables below */
$message = '';
$error = '';
if(isset($_POST["submit"])) /*checking below for on submission*/
{
/*If any of the fields left empty then below msg will be displayed */
if(empty($_POST["name"]))
{
$error = "<label class='text-danger'>Enter Name</label>";
}
else if(empty($_POST["type"]))
{
$error = "<label class='text-danger'>Enter Transport Type</label>";
}
else if(empty($_POST["mileage"]))
{
$error = "<label class='text-danger'>Enter Mileage on your
transport</label>";
}
else /*if all the fields are filled then below will execute */
{
if(file_exists('classinfo.json'))
{
$current_data = file_get_contents('classinfo.json');
/*first decode json data in a variable called array_data so we
can edit and encode back*/
$array_data = json_decode($current_data, true);
/*putting the contents in a var called extra that has been
entered in the form */
$extra = array(
'name' => $_POST['name'],
'type' => $_POST["type"],
'mileage' => $_POST["mileage"]
);
$array_data[] = $extra; /* putting the whole array in a new
record in json*/
$final_data = json_encode($array_data);
if(file_put_contents('classinfo.json', $final_data)) /*if data
send successfully then displaying the below message */
{
$message = "<label class='text-success'>File Appended
Success fully</p>";
}
}
else
{
$error = 'JSON File not exits';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Write Data to JSON file</title>
</head>
<body>
<br />
<div class="container" style="width:500px;">
<h3 align="">Write Data to JSON file - by Sam</h3><br />
<form method="post">
<?php
if(isset($error))
{
echo $error;
}
?>
<br />
<label>Name</label>
<input type="text" name="name" class="form-control" /><br/>
<label>Type of transport</label>
<input type="text" name="type" class="form-control" /><br/>
<label>Mileage</label>
<input type="text" name="mileage" class="form-control"/>
<br/>
<input type="submit" name="submit" value="Append"/><br />