I am brand new to PHP and I thought my code was working but there seems to be a slight bug.
This is my code:
<?php
$string = file_get_contents("jsontest.txt");
$result = json_decode($string);
if(isset($_POST['value']) && !empty($_POST['value']) &&
isset($_POST['whatElement']) && !empty($_POST['whatElement']) &&
isset($_POST['category']) && !empty($_POST['category']) &&
isset($_POST['model']) && !empty($_POST['model'])) {
$value = $_POST['value'];
$whatElement = $_POST['whatElement'];
$category = $_POST['category'];
$model = $_POST['model'];
}
$result->$category->$model->$whatElement = $value;
echo $result->$category->$model->$whatElement;
$myfile = fopen("jsontest.txt", "w") or die("Unable to open file!");
$txt = json_encode($result);
fwrite($myfile, $txt);
?>
I was using this as a response to an HTML input tag. If it is relevant this is the javascript code that I use to call my PHP script
function handleEnter(value, type, exactModel)
{
var bothParts = exactModel.split("_");
category = bothParts[0];
model = bothParts[1];
$.ajax({
url: "morework.php",
data: {value: value, whatElement: type, category: category, model: model},
type: 'post',
success: function(ret){
//location.reload();
console.log(ret);
}
})
}
This passes the proper data to the PHP script but when the "value" variable is set as 0 I get the following: "Fatal error: Cannot access empty property in..."
I have tried to change the code as follows:
Instead of: $result->$category->$model->$whatElement = $value;
I put: $result->category->model->whatElement = $value;
This seems to handle the error but does not change the json file at all. Whereas if I had the original it does not work for 0 but does change the json file for all other numbers.
I have used var_dump on $_POST and in all cases this seems to hold the correct values. However if I do send in a 0 if I echo this line: echo "$value $whatElement $category $model";
it shows up as empty whereas it is populated when non-zero
Example of the var_dump for a 0 value test:
array(4) {
["value"]=>
string(1) "0"
["whatElement"]=>
string(8) "Borrowed"
["category"]=>
string(9) "Category"
["model"]=>
string(8) "Model"
}
An explanation as to what is happening/advice on how to remedy this is greatly appreciated.