0

I have this below JsonArray send from API, I want to save it to the database, but I can't get the data of the Array, always is a blank.

[{
 "user": 7,
 "states": true
}, {
 "user": 13,
 "states": true
}, {
 "user": 10,
 "states": false
}]

This is what I tried to get the JsonArray

if($_SERVER['REQUEST_METHOD']=='POST'){

 $jsondata = json_decode(file_get_contents("php://input"),true);

    $user= $jsondata['user'];
    $status = $jsondata['states'];

    $Query = "insert table(user,states,) 
    values ('$user','$status ')";
}

Thank You

Jimale Abdi
  • 2,574
  • 5
  • 26
  • 33
  • Try var_dumping $jsondata and seeing what the result is. – Mark Nov 21 '19 at 14:00
  • `$jsondata['user']` – your JSON data does not have a property named `user` on the top level. Your problem here seems to be less the read-JSON-from-POST part, but that you don’t actually know how to handle your data structure in the first place …? You have an array on the top level, so you need to either access a specific item by index first, or loop over all of them. – 04FS Nov 21 '19 at 14:04
  • did u tried the solution? – devpro Nov 21 '19 at 15:19

1 Answers1

1

$jsondata consist on multi dimensional array, your array looks like:

Array
(
    [0] => Array
        (
            [user] => 7
            [states] => 1
        )

    [1] => Array
        (
            [user] => 13
            [states] => 1
        )

    [2] => Array
        (
            [user] => 10
            [states] => 
        )

)

And you are trying to insert without using any specific index or not using any loop.

Solution is that, you need to use loop here to store multiple rows in your database.

Second solution is that, you can store this data as same as it is, means, save data in json format in one column rather then to store in multiple rows and multiple column, whenever you need to fetch record or need to show your data, you can just use json_decode().

Side note: i hope (user,states,) last comma is just a typo here.

devpro
  • 16,184
  • 3
  • 27
  • 38