0

I previously had this code to take in data from a form and put it into a JSON file. It was working and after a few months I came back to my website and it began producing errors. The code below takes in the data and analyzes it for and if both are true, it will put that information in the JSON.

    $postTitle =$_POST['postTitle'];
    $postBody =$_POST['postBody'];


    //pass
    $postTitlePass ="no";
    $postBodyPass ="no";


    if(str_word_count($postTitle)>=1){
      $postTitlePass ="yes";
    }
    if(str_word_count($postBody) >= 40){
      $postBodyPass ="yes";
    }

    if($postTitlePass == "yes" && $postBodyPass == "yes"){
                

                    
                    
                    $postData = array('postTitle' => $postTitle,'postBody' => $postBody);
                    
                
                    
                    $inp = file_get_contents('data.json');
                    $tempArray = json_decode($inp);
                    $data = $postData;
                    array_push($tempArray, $data);
                    $jsonData = json_encode($tempArray, JSON_PRETTY_PRINT);
                    file_put_contents('data.json', $jsonData);
  }
  • 2
    "_and it began producing errors_" What errors would that be? – brombeer Oct 31 '20 at 17:20
  • 1
    You need to `json_decode($inp, true)` to return an array from your JSON. `array_push` doesn't work on objects. The error would presumably be *`Warning: array_push() expects parameter 1 to be array, object given`*. Useful reading: [json\_decode to array](https://stackoverflow.com/questions/5164404/json-decode-to-array) – Markus AO Oct 31 '20 at 18:08
  • On another note. PHP has `boolean` type variables, `true/false`, that can be used in place of "yes" and "no" strings. Consider doing instead `$postTitlePass = str_word_count($postTitle)>=1); // returns true or false`. Then you can simply do `if($postTitlePass && $postBodyPass)`. Which is equivalent to `$postTitlePass === true`, etc. – Markus AO Oct 31 '20 at 18:12

1 Answers1

0

Your file is output as json $tempArray = json_decode($inp); Must be converted to an array

$tempArray = (array)json_decode($inp);

The description of array_push is as follows

function array_push (array &$array, ...$vars) {}