Update JSON data that is stored in Database - php

I have JSON data that is stored in a variable which is a set of permissions for a particular user. The JSON data however, is not stored in a file, it's just in a database column.
I've tried to look for a method of updating a permission (which is either true or false) but I've had no luck thus far. At the moment, I have something to the effect of;
The raw JSON data...
{
"permissions": {
"permission_1": true,
"permission_2": false
}
}
Getting it out of the database...
$permissions = json_decode($data, true);
How do I (using PHP) update the JSON data to say, update permission 2 to true? I'm using json_decode() when it comes out of the database and putting it into an array but that's only for using it. After that I'm lost as to how to update the value.

In order:
Extract column data from the database.
"SELECT column FROM table WHERE id = 1 LIMIT 1"
JSON_decode data into a set of PHP values/objects/arrays/whatever.
$array = json_decode($OutputRow['column'],true);
Update the value(s) you need to update.
$array['permissions']['permission2'] = true;
Recompile into a JSON string using JSON_encode.
$data = json_encode($array);
Update the database (SQL?) with the new JSON_encoded string.
"UPDATE table SET column = :data WHERE id = 1 LIMIT 1"
My examples use PDO and MySQL by reference but does not go into any details about database interaction as you've not given any details as to how you're reaching your database. It's only a ballpark rough example of how to do the points listed.

Related

modify the property value of JSON string stored in the Table Column

I have JSON string stored in my database column. I have to update that value in JSON string.
Here Is my table.
I want to update the state value inside it.
Example:
Name1 has State value KA so I want to update it to GJ.
What I have Tried So far?
UPDATE Customer
SET Detail = JSON_MODIFY(Detail , '$.Address.State', 'KA')
WHERE Name = 'name1';
Also Tried JSON_REPLACE is also not working.
But it shows the error:
FUNCTION Customer.JSON_MODIFY does not exist
Note: I know one workaround to do this but I didn't Want to fetch that string and update it completely. I want to update the particular detail in string.
I have also created the SQL Fiddle.
I am doing this on localhost. Below are the localhost detail.
Database server
Server: localhost (localhost via TCP/IP)
Software: MySQL
MySQL Version :5.5.24
phpMyAdmin
Version information: 3.5.1, latest stable version: 4.7.3
12.16 JSON Functions
...
Unless otherwise indicated, the JSON functions were added in MySQL
5.7.8.
...
Try:
UPDATE `Customer`
SET `Detail` = JSON_REPLACE(`Detail`, '$.Address.State', 'GJ')
WHERE `Name` = 'name1';
See db-fiddle.
As #wchiquito already pointed out, the JSON function were added in MySQL 5.7.8.
If you are not able to upgrade your MySQL installation you will have to take the workaround you mentioned. Using regular expression to replace your value is also not going to work without being able to define custom mysql functions. (Also there is a lot that can go wrong if you do operations like this with regex...)
So the only options I see you have, are:
upgrade your installation (award to #wchiquito).
Fetch the column, parse it and update it. Just as you mentioned yourself as a workaround.
That could look something like this:
// fetch the details
$sth = $pdo->prepare('select `Detail` from `Customer` where `Name` = ?');
$sth->execute(['name1']);
$detail = json_decode($sth->fetchColumn(), true);
// modify the state
$detail['Address']['State'] = 'KA';
// update the details
$sth = $pdo->prepare('update `Customer` set `Detail` = ? where `Name` = ?');
$sth->execute([json_encode($detail), 'name1']);
But I recommend just upgrading your MySQL installation if possible.
As you have an old MySQL, fetch the JSON string, decode it to an array, edit the array, re-encode it, and update your row:
// Fetch row
$json = $row['columnName'];
$array = json_decode($json, true); //true creates array and not stdClass
$array['valueToChange'] = 'some new value';
$json = json_encode($array);
// Perform update query
You can:
Use JSON_INSERT function to add the property to the object if it is not exist
Use JSON_REPLACE function substitutes the property only if it is exist
Use JSON_SET function to add the property if it is not found then replace it.
Hope this helps!

JSON data handling with mySQL and php

For the past 2 days I have been looking over the internet on how to handle data stored as json in mySQL database.All I found was a single article in here which I followed with no luck.So here is my question
This is my table called additional with 2 columns only...jobid and costs. jobid is an int of length 5 and obviously the primary key, costs is simply stored as text. Reason I combined all the costs under one column is because the user in my application can put whatever he/she wants in there, so to me the costs is/are unknown. For example one entry could be
24321 , {"telephone" : "$20"}
or
24322 , {"telephone" : "$20", "hotel" : "$400"}
and so on and so forth but I hope you get the point.
Now given this example I need to know how to handle data in and out from the database stored as json using php. So insert, select and update but I think with one given example I can do the rest If someone can help me understand how to handle json data in and out from a database.
Oh and one last thing. Not only I need to know how to fetch the data I need to be able to separate it too e.g:
$cost1 = {"telephone" : "$20"};
$cost2 = {"hotel" : "$400"};
I really hope someone can help with this because like I said above I spent 2 days trying to get my head around this but either no articles on this matter(except the one from this site) or completely irrelevant to my example
You tagged it as PHP so you can use php functions: json_encode and json_decode.
For example when you read (SELECT) and got this cost value in string corresponding to the primary key 24322:
//after you query db and got the cost in string...
$sql = "SELECT * FROM additional";
$result = mysqli_query($conn,$sql); $row = mysqli_fetch_array($result);
//from your comment below.... just changed to $cost so I don't have to change everything here...
$cost = $row['costs'];
//$cost = '{"telephone" : "$20", "hotel" : "$400"}'
//you just have to:
$cost = json_decode($cost);
// result in an object which you can manipulate such as:
print_r($cost->telephone);
// $20 or:
print_r($cost->hotel);
//$400;
//or if you want to go through all of the costs... you change that to array:
$cost = (array)$cost; //or on your json_decode you add a TRUE param... ie(json_decode($cost, TRUE))...
print_r($cost);
//will produce an associative array: ['telephone'=>'$20', 'hotel'=>'$400']
//for which you can do a foreach if you want to go through each value...
On the other hand when you save to db with an object:
$cost = (object)['hotel'=>'$300', 'taxi'=>'$14'];
//you json_encode this so you can write to db:
$cost = json_encode($cost);
//a string... you can then use $cost to write to db with (insert, update, etc)
Note: json_decode needs the input string to be UTF-8 encoded. So you might need to force your mysql server to provide UTF-8. Some reading: https://www.toptal.com/php/a-utf-8-primer-for-php-and-mysql
Hope this helps...
You can use json_encode() and json_decode() throughout your update or insert process.
Basically
json_encode() takes Array and returns JSON as String
json_decode() takes JSON as String and returns Array
http://php.net/manual/en/function.json-encode.php
So in your case whenever you want to update 24321 , {"telephone" : "$20"}
you got to decode like
$array = json_decode($row['jsonDataOrWhateverTheColumnNameIs'],true);
$array['telephone'] = "40$";
...
...
$jsonString = json_encode($array); // Use this string with your update query.

unserialize data from mysql

in my mysql cell this is stored using serialize function
a:1:{i:0;s:275:"a:4:{s:8:"khghg_id";s:10:"foo1187";s:3:"uri";s:21:"foo/vtory/1187";s:4:"name";s:5:"nmart";s:5:"tuhlmb";a:3:{i:0;s:40:"knuujhs/201205/13_03_pceb9.jpg";i:1;s:40:"knuujhs/201205/13_03_0wlih.jpg";i:2;s:40:"knuujhs/201205/13_03_tq5wf.jpg";}}";}
i am trying to do unserialize
i am using this code
$cell =$row9['attachment'];
$list = unserialize($cell);
$info = unserialize($list[0]);
var_dump($info);
when i am trying with this i am getting error bool(false) error
so i tried with parse_str
with parse_str i did not get any error
parse_str($cell,$list );
but i am not getting the output in my database
i am storing the output in database and i am submitting the query to database .everything is getting stored other than this unserialize values .here u can note that there are
khghg_id which is foo1187
uri which is foo/vtory/1187
name which is nmart
i want to store these details in my database so i am using
'.$info['khghg_id'].' for sending the data to mysql but mysql stores everything other than all unsterilized values
You retrieve a serialized text from database.
You unserialize it.. change it and then when you save it back to database you need to serialize it back
//retrieve serialized data from database
$arr = unserialize($row['properties']);
//get the desired value
$khghg_id = $arr['khghg_id'];
//now insert $khghg_id in database
From the code you posted above.. I see you are unserializing 2 times.. you dont really need to do this
$cell =$row9['attachment'];
$list = unserialize($cell);
$info = $list[0]; //this line should make the difference
var_dump($info);

How to update serialize data in MySQL

I have this serialize data in my mySQL database
a:4:{i:0;s:7:"bvl.png";i:1;s:8:"ccop.jpg";i:2;s:11:"reyborn.png";i:3;s:13:"swopgroup.jpg";}
How can I update this data, for example I want to delete ccop.jpg?
Do not store serialized data in database.
Create a linked table consists of main_id and picture and store your image names in it.
So, you will have distinct access to them.
You have to fetch the value from the database, unserialize it, remove the element, serialize it and save again.
$remove = "ccop.jpg";
//
// get the string from the database
//
$arr = unserialize($str);
foreach($arr as $key => $value)
if ($value == $remove) unset($arr[$key]);
$str = serialize($arr);
//
// save the string back to the database
//
Instead of saving serialized list of values, it's better to have a normalized database and just do a simple DELETE FROM images WHERE object_id = ....
Ideally you need to
extract it
deserialize it
modify it
serialize it
write it back to the database.
Since you are storing it in a VARCHAR field and it is a PHP serialized array you would want to pull it out of the database unserialize and then re-update the field. You shouldn't look to MySQL to modify PHP specific information because well ... that's not what it is made for.

Unserialize values from mySQL

I am using a classified scripts and saves user_meta data in the wp_usermeta table.
The meta_key field is called user_address_info and in it there are all the data like below :
s:204:"a:7:{s:9:"user_add1";s:10:"my address";s:9:"user_add2";N;s:9:"user_city";s:7:"my city";s:10:"user_state";s:8:"my phone";s:12:"user_country";N;s:15:"user_postalcode";s:10:"comp phone";s:10:"user_phone";N;}";
I am not using all the fields on the script but user_add1, user_city, user_state and user_postalcode
I am having trouble to get the data using SQL like the example below (wordpress) :
$mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_A);
I would like some help here so that I will display anywhere (I dont mind using any kind of SQL queries) the requested info e.g. the user_city of current author ID (e.g. 25)
I was given the following example but I want something dynamic
<?php
$s = 's:204:"a:7:{s:9:"user_add1";s:10:"my address";s:9:"user_add2";N;s:9:"user_city";s:7:"my city";s:10:"user_state";s:8:"my phone";s:12:"user_country";N;s:15:"user_postalcode";s:10:"comp phone";s:10:"user_phone";N;}"';
$u = unserialize($s);
$u2 = unserialize($u);
foreach ($u2 as $key => $value) {
echo "<br />$key == $value";
}
?>
Thank you very much.
No, you can't use SQL to unserialize.
That's why storing serialized data in a database is a very bad idea
And twice as bad is doing serialize twice.
So, you've got nothing but use the code you've given.
I see not much static in it though.
do you experience any certain problem with it?
Or you just want to fix something but don't know what something to fix? Get rid of serialization then
i have found that the serialize value stored to database is converted to some other way format. Since the serialize data store quotes marks, semicolon, culry bracket, the mysql need to be save on its own, So it automatically putting "backslash()" that comes from gpc_magic_quotes (CMIIW). So if you store a serialize data and you wanted to used it, in the interface you should used html_entity_decode() to make sure you have the actual format read by PHP.
here was my sample:
$ser = $data->serialization; // assume it is the serialization data from database
$arr_ser = unserialize(html_entity_decode($ser));
nb : i've try it and it works and be sure avoid this type to be stored in tables (to risky). this way can solve the json format stored in table too.

Categories