1
I’m starting a php Emm studies and want to be able to do a crud using a json. I already managed to create the file and write in it, I can also read the data. But I’m having a problem. The first time, when I play the file and throw the data in it empty, it works well, but the second time, the file already brings me a wrong structure of the json file. How can I fix this?
My code:
<?php
if(isset($_POST['submit'])) {
$nome = $_POST['nome'];
$email = $_POST['email'];
$telefone = $_POST['telefone'];
$dados_preenchidos = array(
'codigo' => rand(1000, 9999)."",
'nome' => $nome,
'email' => $email,
'telefone' => $telefone
);
$dados = array($dados_preenchidos);
$dados_json = json_encode($dados);
$fp = fopen("bd/dados.json", "a");
$escreve = fwrite($fp, $dados_json);
fclose($fp);
header('Location: index.php');
}
?>
Sore o JSON:
At first, it creates and generates the data like this:
[{"code":"3709","name":"Samuel","email":"[email protected]","phone":"123456789"}]
All right, that’s correct and it appears on the screen for me straight, but when I enter a second record, it looks like this:
[{"code":"3709","name":"teste1","email":"[email protected]","phone":"1234567897"}][{"code":"8718","name":"teste2","email":"[email protected]","phone":"789456123"}]
Notice that the "[" repeats itself, when it should be like this:
[{"code":"3709","name":"teste1","email":"[email protected]","phone":"1234567897"},{"code":"8718","name":"teste2","email":"[email protected]","phone":"789456123"}]
I did the test by changing the hand to the correct form and the code worked perfectly...
How I do?
Leandro, thank you for the reply, but you made an error in your code, on the line
$dados_json = json_encode($dados_preenchidos);
, the mistake is this:Parse error: syntax error, unexpected '$dados_json' (T_VARIABLE)
– SaMuK
corrected. Missed one ; in line above; Can test
– user148170
Dude. It still didn’t work, error on that line now:
$arquivo = file_get_contents('dados.json');
– SaMuK
bd/data.json I will change the response
– user148170
I saw it, and I tried to change it too, but continued with the error kkk
– SaMuK