I am trying to save json array in mysql, but getting error. First, i had tried to save it as a string using implode function. But not getting same string while fetch data. Now trying to save json string as it is.So that i can fetch it easily.This is json string
{"us_id":"1","stu_id":"6","class_id":"3","req_x":[
{ "u_id":"1", "u_details":"testing user", "charges":"12.50"},
{ "u_id":"2", "u_details":"testing user 2", "charges":"10.50" },
{ "u_id":"3", "u_details":"testing user 3", "charges":"9.50" }
]}
And i need to save req_x field in diff column in db
$req_x = '[
{ "u_id":"1", "u_details":"testing user", "charges":"12.50"},
{ "u_id":"2", "u_details":"testing user 2", "charges":"10.50" },
{ "u_id":"3", "u_details":"testing user 3", "charges":"9.50" }
]';
And this is code saving json string using implode
$req_dets= implode("&",array_map(function($a) {return implode("|",$a);},$req_x));
Now i am trying to save it using simply
json_decode($req_x)
But it's not working. Returns error json_decode() expects parameter 1 to be string array given
CodePudding user response:
If you are starting with this JSONstring
$start =
'{ "us_id":"1",
"stu_id":"6",
"class_id":"3",
"req_x":[
{ "u_id":"1", "u_details":"testing user", "charges":"12.50"},
{ "u_id":"2", "u_details":"testing user 2", "charges":"10.50" },
{ "u_id":"3", "u_details":"testing user 3", "charges":"9.50" }
]
}';
And you only want to save the req_x
array to the database....
$obj = json_decode($start);
$arr = $obj->req_x;
// make a json string of that
$json_req_x = json_encode($arr);
echo $json_req_x;
RESULT is a JSONString
[
{"u_id":"1","u_details":"testing user","charges":"12.50"},
{"u_id":"2","u_details":"testing user 2","charges":"10.50"},
{"u_id":"3","u_details":"testing user 3","charges":"9.50"}
]
Now you can put the string $json_req_x
into your database using an INSERT or UPDATE as you would with any other column.
CodePudding user response:
What is the data type for that column? To store JSON data try changing the column data type to JSON.