0

Hello I Have This Php Code:

$Name = $_POST["Name"];
$sobrenome = $_POST["sobrenome"];
$data_time = $_POST["data_time"];
$data = array(
    array(
        "nome" => $Name,
        "sobrenome" => $sobrenome ,
        "data" => $data,
    ),
);
$arquivo = 'form.json';
$json = json_encode($data);
$file = fopen(__DIR__ . '/' . $arquivo,'w');
fwrite($file, $json);
fclose($file);

as you can see it converts my form into an array and saves it in a json file so far so good, but the problem is that if I send the form more than once it subscribes to the current data, how could I create a new array each does it already exist?

edit: here's an example, suppose when i sent the form the first time i put the value in nome: Nicolas and Sobrenome: Baiger and last in data_time i put 18:31, so form.json would look like this:

'[{"nome":"Nicolas", "Sobrenome":"Baiger", data_time:"18:31"}]'

Now if I put in the nome: Jhon in the Sobrenome: Clynton and in data_time: 12:30 and I submit the form a second time it would overwrite all the other data that I had previously put in like this:

'[{"nome":"Jhon", "Sobrenome":"Clynton", data_time:"12:30"}]'
kmoser
  • 8,780
  • 3
  • 24
  • 40
Nick branly
  • 13
  • 1
  • 3
  • I'm not sure I understood correctly, but it seems to me you want to [append](https://stackoverflow.com/questions/24972424/create-or-write-append-in-text-file) to the file? – El_Vanja May 16 '21 at 02:00
  • yes, but before I want to create a new array if items already exist in json – Nick branly May 16 '21 at 02:04
  • You mean you want to update some values? It's really not clear what you're asking, can you show it on a simplified example? – El_Vanja May 16 '21 at 02:06
  • here is an example if if there is a key "nome" in form.json it creates a new array that also has the key "nome" because the way my code is it is overwriting the data and I do not want it to subscribe to Dice! – Nick branly May 16 '21 at 02:12
  • 1
    I'm sorry, that doesn't clear things up. Please edit the question and give an example of how the file should look like after one and after two submissions. – El_Vanja May 16 '21 at 02:16
  • @El_Vanja I already edited the post to see if it was clearer! – Nick branly May 16 '21 at 02:37
  • This confirms my first impression, you just want to append a new entry (add new information to the end of the file). The question I linked to and the answer you got here both show how to append. – El_Vanja May 16 '21 at 08:50

1 Answers1

0

The description kinda blur, but I guess there are two possibilities:

  1. Append the second post into form.json.

change $file = fopen(DIR . '/' . $arquivo,'w') to:

$file = fopen(__DIR__ . '/' . $arquivo,'a');
  1. use a different json file:

change $arquivo = 'form.json'; to :

$arquivo = random_int(100,999) . 'json';