Skip to content
Advertisement

How can I read/ write to a single array in json with PHP

I have a simple script that can store data in a json file. Every time you save the form it creates a new array. I just want to update goal and raised in the same array.

form:

<form action="process.php" method="POST">
Goal:<br>
<input type="text" name="goal">
<br><br/>
Raised:<br>
<input type="text" name="raised">
<br><br>
<input type="submit" value="Submit">
</form>

process.php

<?php

$myFile = "data.json";
$arr_data = array();

try
{      
    $formdata = array(
        'goal'=> $_POST['goal'],
        'raised'=> $_POST['raised']
    );

    $jsondata = file_get_contents($myFile);

    $arr_data = json_decode($jsondata, true);

    array_push($arr_data,$formdata);

    $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

    if(file_put_contents($myFile, $jsondata)) {
            echo 'Data successfully saved';
        }
    else 
            echo "error";

}
catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "n";
}

?>

Advertisement

Answer

array_push appends. You want to replace existing, not add, right? So:

<?php

$myFile = "data.json";

try {      
    $arr_data = json_decode(file_get_contents($myFile), true);

    // don't forget to validate first of course:
    $arr_data['goal'] = $_POST['goal'];
    $arr_data['raised'] = $_POST['raised'];

    $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

...
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement