我可以通过以下编码成功地将新数据写入json文件,但它不会显示消息-File Append成功,这是在PHP的最后一位中定义的。请告诉我我在哪里错了?如果窗体字段保留为空,我确实会显示错误消息,这很好,但是我真的希望成功数据写入后显示成功消息,相反,该页面从头开始,我可以添加新数据,然后。 预先感谢。
<?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 />
答案 0 :(得分:0)
您需要在某个地方echo
:
$message = "<label class='text-success'>File Appended
Success fully</p>";
echo $message;
HTML无效。或者您打开<p>
或关闭</label>