I have a database where I store some data, and one field is a json string.
I insert an json in this field:
$stmt->bindParam(":settings", json_encode($widget->settings));
Then when I try to retrieve the record I get my row with the settings column as string. I need my data to be json, so I should decode this field before output my records. If i go with:
$app->response->setBody(json_encode($data, JSON_NUMERIC_CHECK));
I get something like:
"name":"My Name","label":null,"row":null,"settings":"{\"site\":\"dfsdf\",\"action\":\"UrlInfo\"}"
with settings escaped. I should first decode settings and then encode again to output my results. How can I do to solve this?
UPDATE:
I retrieve my data using PDO, so I get an array:
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
Before I save this I have:
"settings":{"site":"fff","action":"UrlInfo"}}
When you retrieve the data, you should use json_decode to reverse the encoding that you did when you inserted it.
foreach ($data as &$row) { // Use reference so we can modify in place
$row['settings'] = json_decode($row['settings']);
}
$app->response->setBody(json_encode($data, JSON_NUMERIC_CHECK));
Related
i want to update my column data in a way that posted data gets appended at the end of the existing column data. Current data is in Json format
This is how i am updating record
$data=array('services', $array );
$this->db->where('id',$id)
$this->db->update('garage',$data);
but this updates whole record how do i append the record at the end of json
You can select the data from the database and use PHP way to concatenate the string and run the update.
$d=$this->db->get_where('garage',array('id',$id))->row();
Now merge the you can merge the existing data with new data.
$new_data=$d->services.json_encode($array);
$data=array('services', $new_data );
$this->db->where('id',$id)
$this->db->update('garage',$data);
Hope this will fix the issue.
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.
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.
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);
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.