I am trying to get input from user and on submission it get save in Json file but i am experiencing errors and there solutions on web did not help me.
Here is my code:
<?php
array()
$arr_data[] = array(); // create empty array
$myFile = "sample.json";
try
{
//Get form data
$formdata = array(
'name'=> $_POST['name'],
'age'=> $_POST['age'],
'sex'=> $_POST['sex'],
'education'=>$_POST['edu']
);
//Get data from existing json file
$jsondata = file_get_contents($myFile);
// converts json data into array
$arr_data = json_decode($jsondata, true);
// Push user data to array
array_push($arr_data,$formdata);
//Convert updated array to JSON
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
//write json data into data.json file
if(file_put_contents($myFile, $jsondata)) {
echo 'Data successfully saved';
}
else
echo "error";
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
Now the form I am using code is here:
<form id="myform" method="post" action="action.php" >
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label> Name</label>
<input type="text" class="form-control" placeholder="Please type Name" value="" name="name" size="20" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Age</label>
<select class="form-control" placeholder="Please Select Education" value="" id="edu" name="edu" required>
<option selected="true" disabled="disabled" >Please Select Type</option>
<option value="eng">Engineer</option>
<option value="doc">Doctor</option>
<option value="res">Researcher</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Age</label>
<input type="number" class="form-control" placeholder="Please specify Age" value="age" id="age" name="age" size="20" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>sex</label>
<input type="text" class="form-control" placeholder="Please specify Sex" value="" id="sex" name="sex" size="50" required>
</div>
</div>
</div>
<button type="submit" class="btn btn-info btn-fill pull-right" id="btn" name="btn"> Submit</button>
<div class="clearfix"></div>
</form>
Now the issue is on submission. I got following errors and nothing on web is helping me. I don't know where I am wrong.
Warning: array_push() expects parameter 1 to be array, null given in /Users/path/action.php on line 34
Warning: file_put_contents(sample.json): failed to open stream: Permission denied in /Users/path/action.php on line 40 error
Thanks in advance for your help and time.