0

I'm trying to put a users "favourite" game into the corresponding file for their user upon post.

if(isset($_POST['favourite'])){

        $filetxt = 'data/users.json';

        $formdata = $_POST['favourite']; //this contains the value "game"

        $arr_data = array();

        if(file_exists($filetxt)) {
            $jsondata = file_get_contents($filetxt);
            $arr_data = json_decode($jsondata, true);
        }

        $arr_data[][$_SESSION['username']]['favourite'] = $formdata;

        $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
        file_put_contents('data/users.json', $jsondata);
}

The file is structured as:

[
    {
        "CNR": {
            "first-name": "test",
            "last-name": "test",
            "email": "test",
            "country": "test",
            "password": "test",
            "favourite": []
        }
    },
    {
        "usertest": {
            "first-name": "test",
            "last-name": "test",
            "email": "test",
            "country": "United States",
            "password": "password",
            "favourite": []
        }
    }
]

Currently it will add the correct data however not into the array, but onto the end.

[
    {
        "CNR": {
            "first-name": "test",
            "last-name": "test",
            "email": "test",
            "country": "test",
            "password": "test",
            "favourite": []
        }
    },
    {
        "usertest": {
            "first-name": "test",
            "last-name": "test",
            "email": "test",
            "country": "United States",
            "password": "password",
            "favourite": []
        }
    },
    {
        "CNR": {
            "favourite": "game"
        }
    }
]

I've tried things like arraypush, splice and other methods however I'm not sure what is the best for this use case. Any thoughts/recommendations on how I can best achieve this with the desired result are greatly appreciated, thanks!

0

4 Answers 4

1
$arr_data[$_SESSION['username']]['favourite'][] = $formdata;

Difference is that I moved [] to the end of the $arr_data.

Sign up to request clarification or add additional context in comments.

2 Comments

Never thought of it, this way. really saves many lines of code. :P
This was very helpful and did have the desired outcome, thank you!
1

Before adding it to array, you need to check if the key exists and then proceed rather than just adding the code.

if(isset($_POST['favourite'])){

        $filetxt = 'data/users.json';

        $formdata = $_POST['favourite']; //this contains the value "game"

        $arr_data = array();

        if(file_exists($filetxt)) {
            $jsondata = file_get_contents($filetxt);
            $arr_data = json_decode($jsondata, true);
        }
 // changes over here
        if(isset($arr_data[$_SESSION['username']])){
            if(isset($arr_data[$_SESSION['username']]['favourite'])){
               $arr_data[$_SESSION['username']]['favourite'][] = $formdata;
            }  else {
               $arr_data[$_SESSION['username']]['favourite'] = $formdata;
            }

        } else {
          $arr_data[][$_SESSION['username']]['favourite'] = $formdata;
        }

        $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
        file_put_contents('data/users.json', $jsondata);
}

1 Comment

Thanks for your help!
0

I can see that most have answered the question but might I also provide some suggestions (food for thought) on your process?

1). Firstly, I can't work out if you are storing ALL users in a single file or if there's a file per user. Example username.json I am going to assume there is a file per username because there should be to make file writes quicker and it would require the main file to be locked for everyone else just because one user is writing to it.

2). I noticed that the favourite part seems to be stored in the _SESSION too. If the _SESSION is storing the same mini array in it (a replica of what is stored in the file) then there's no point in opening the file to write a single value and then save it again. You may as well just write over the existing file straight away. Like this...

$writeToFile = json_encode($_SESSION[mydata]);
$fh = fopen("/path/to/username.json","w+");
fwrite($fh,$writeToFile);
fclose($fh);

// You could also use file_put_contents but most prefer
// to use fopen()

3). I will assume the passwords you are storing are encrypted and nobody can type [yourdomain]/users/username.json to see the raw output of the json files. You might want to ensure .json files aren't accessible from the browser. You can do that with .htaccess.

1 Comment

Thanks for the tips! This is a piece of coursework I'm working on and wont be a live site or anything, purely for the assignment. They are stored in plain .json however we've been instructed to use this and aren't allowed to use a secured database or anything along those lines.
-1

Problem is in this code, you are creating every time a new sub array: Change this:

$arr_data[][$_SESSION['username']]['favourite'] = $formdata;

To this

if(isset($arr_data[$_SESSION['username']])) {
  $arr_data[$_SESSION['username']]['favourite'] = $formdata;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.