I have a php array like the one below.
$arr = array(
array(
"date"=>date('Y-m-d'),
"message"=>"test message 1",
"from_id"=>21,
"to_id"=>14
),
array(
"date"=>date('Y-m-d'),
"message"=>"test message 2",
"from_id"=>23,
"to_id"=>12
)
);
I do a json_encode on this array to convert it json.
$jsonarr = json_encode($arr);
Output of $jsonarr:
[
{"date":"2012-11-22","message":"test message 1","from_id":21,"to_id":14},
{"date":"2012-11-22","message":"test message 2","from_id":23,"to_id":12}
]
After that i insert this in mysql table. Everything is fine till here.
Now i have to update this with another json by concatenation.
Another JSON:
[
{"date":"2012-11-22","message":"test message 3","from_id":28,"to_id":2},
{"date":"2012-11-22","message":"test message 4","from_id":53,"to_id":72}
]
And i want the field in my mysql table to display like this:
[
{"date":"2012-11-22","message":"test message 1","from_id":21,"to_id":14},
{"date":"2012-11-22","message":"test message 2","from_id":23,"to_id":12},
{"date":"2012-11-22","message":"test message 3","from_id":28,"to_id":2},
{"date":"2012-11-22","message":"test message 4","from_id":53,"to_id":72}
]
How can i write an UPDATE query for this.
I can do this by using 2 queries. One select query then formatting the field and later updating. But can this be achieved with one query ?
The solution to your immediate problem is this:
MySQL does not natively support JSON values. You need to fetch the value from the database:
Then modify it in the PHP script:
Then update it in the DB:
Make sure this happens in a transaction. Also, you need to use the InnoDB storage engine.
But the more interesting question is why do you need to store JSON in the DB? Why not use a separate table:
Then you could simply insert into that table. That’s the correct way of doing this. If you don’t have a very good reason to use JSON, I would suggest getting rid of it.