I want to Save Serialized array in Mysql Database.
I want final result when save value in database looks like in below format:
a:1:{i:5;s:2:"2,";}
Please provide solution starting from how to make this kind of array and simple sql query (insert or update query).
Below is the code which i used:
<?php
$a = array (
'5' => '2,'
);
$b = serialize($a);
?>
and i use $b variable in sql query. But my data not save in my expected format.
Just to give you simple directions. Youll need to parse data from wherever you are passing from in Json format (object or an array). Then in php use json_encode
And as # Richard said youll need to grasp these on your own then post some code youve tried but probably fails.
Related
I am using a jQuery plugin of nestable forms and storing the order of these in a database using serialize (achieved through JS). Once I retrieve this data from the database I need to be able to unserialize it so that each piece of data can be used.
An example of the data serialized and stored is
[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]
The number of ID's stored in each serialized data varies and the JS plugin adds the [ and ] brackets around the serialization.
I have used http://www.unserialize.com/ to test an unserialization of the data and it proves successful using print_r. I have tried replicating this with the following code:
<?php
print_r(unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]'));
?>
but I get an error. I am guessing that I need to use something similar to strip_tags to remove the brackets, but am unsure. The error given is as follows
Notice: unserialize(): Error at offset 0 of 70 bytes
Once I have the unserialized data I need to be able to use each ID as a variable and I am assuming to do so I need to do something as:
<?php
$array = unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]');
foreach($array as $key => $val)
{
// Do something here, use each individial ID however
// e.g database insert using $val['id']; to get H592736029375 then K235098273598 and finally B039571208517
}
?>
Is anyone able to offer any help as to how to strip the serialized data correctly to have the ID's ready in an array to then be used in the foreach function?
Much appreciated.
PHP's serialize() and unserialize() functions are PHP specific, not for communicating with other languages.
It looks like your JS serialize function is actually generating JSON though, so on the PHP side, use json_decode() rather than unserialize.
Here's a fiddle
$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $index=>$data){
echo "$index) {$data['id']}\n";
}
Outputs:
0) H592736029375
1) K235098273598
2) B039571208517
I simply need to store text (rows have their own separate date).
Either...
1. How do I read (either of) the following value(s) in to a PHP array that I can iterate over via a foreach loop?
...or...
2. how do I INSERT INTO a table a value assigned to a key (which is not clarified at all in the PostgreSQL documentation)?
{".022 x 2.031"}
{".012 x 3.621"}
So I currently have single measurement values (to be treated as text purely for records) formatted as the first format above. I try to convert the row data in PHP and get Invalid argument supplied for foreach() for the following:
$array = json_decode($row1['material_size']);
foreach ($array as $k1) {echo $k1;}
So after doing even more searching and reading I decided to see if I could just convert the data via PostgreSQL directly:
SELECT array_to_json(material_size) AS material_size FROM table;
Now I get the array data correctly...
$array = json_decode($row1['material_size']);
print_r($array);
Array
(
[0] => .022 x 2.031
)
Afaik, dimension is a structured data. If your data is 2 dimensional, you may use the point datatype or create your own composite type. I'd suggest to use Pomm to get it converted to a PHP array.
If you want to stick with Json then you can select on keys like stated in the documentation but you need to overwrite the complete JSON value every time you want to update a value.
I am trying to merge a static data with json encode array data for output. Here is my php code:
$arr = array();
$rs = mysql_query("SELECT id, name, picture, mail, gender, birthday FROM users WHERE id='$logged_id' ");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":'.json_encode($arr).'}';
Now I want to merge other data with it:
$user_ip = array("user_ip" => $user_ip_address);
I have tried array_merge($arr, $user_ip). But it didn't work. I think this is not correct json array format if I merge with existing data array. Please let me know what to do how to output other data as well as current data coming from mysql with json encode.
I am getting such output with my existing code, which is correct:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11"}]}
But now I want to add other variable e.g $user_ip_address as user's data joining with current output data like this:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11",user_ip:"127.0.0.1"}]}.
I want to get it in this way. How to do it? Please let me know. Thanks in advance.
try this:
echo json_encode(array('users' => $arr, 'user_ip' => $user_ip_address));
on a side note:
you should use PHP PDO class to connect and query the database.
mysql_fetch_object returns an object, not an array. So, what are you doing by $arr[] = $obj; is just adding an object into an array. So, the actual structure of the $arr is something like
$arr => [
[0] => Object(....),
[1] => Object(....),
....
]
In your particular case, I assume you are fetching single row by primary key, so there are only one object.
THe simpliest way to fix this is to add a field to an object. I haven't worked with PHP since 5.3, so can't be sure, but it's as simple as adding
$obj->user_ip = $user_ip_address;
inside the loop.
Btw, a couple of questions for you:
Why do you use loop if it should result in a single row?
Why you are embedding the variable directly into SQL query. It's quite vulnerable, read about sql-injections and how to prevent it (one day I was really tired telling people here on SO to use PDO and prepared statements, so just go read about it),
Have you read the documentation about mysql_fetch_object and array_merge? Why not (because if you have read it you wouldn't be asking the question).
Tried debugging? E.g. attaching a debugger and watching for variables contents? Inserting logging or (God forgive me) debug print with echo?
"Didn't work" is a quite bad error description. This time you was lucky, because the error was obvious. Next time, please, be more specific.
So im trying to figure out the best way to get MySql table data into either a multidimensional PHP array or convert that multidimensional array into a json string.
Essentially what im trying to do is have a php include that returns the JSON string so i can iterate through it. I am needing a single key with multiple values, so im not 100% sure that im headed in the right direction.
I want to assign multiple values to the same key, for example:
[{"key1": "package1", "package2", "package3"}, {"key2": "package1", "package2", "package3", "package4"}]
I think that is not going to work right? Because i dont have any type of index's?
That is not valid JSON. The structure you are looking for would be something like:
[
{"key1": ["package1", "package2", "package3"]},
{"key2": ["package1", "package2", "package3", "package4"}]
^ An array as the value to the key "key1", "key2", etc..
]
At the PHP side, you would need something like:
For every row fetched from MySQL
$arr[$key] = <new array>
for each package:
append package to $arr[$key]
echo out json_encode($arr)
JS arrays have an implicit array keying, starting at index 0. What you've got is a perfectly valid JS array, the equivalent of having written:
var x = []; // create new empty array
x[0] = {"key1": .... }; // first object
x[1] = {"key2": ....} // second object
Note that the contents of your {} sub-objects is NOT valid.
You should never EVER built a JSON string by hand. It's too unreliable and easy to mess up. It's just easier to use a native data structure (php arrays/objects), then json_encode() them. Ditto on the other end of the process - don't decode the string manually. Convert to a native data structure (e.g. json_decode(), JSON.parse()) and then deal with the native structure directly.
essentially, JSON is a transmission format, not a manipulation format.
Welcome Stackoverflow nation ! I'm trying to decode json encoded string into SQL statement withing php.
Lets say I've such a json encoded string =>
$j = '{"groupOp":"AND","rules":[{"field":"id","op":"cn","data":"A"},{"field":"i_name","op":"cn","data":"B"}]}';
I want to build SQL WHERE clause (needed for filterToolbar search in jqGrid), something like this => "WHERE id LIKE %A% AND i_name LIKE %B% " and etc.
I've done this =>
$d = json_decode($j);
$filterArray = get_object_vars($d); // makes array
foreach($filterArray as $m_arr_name => $m_arr_key){
// here I can't made up my mind how to continue build SQL statement which I've mentioned above
}
Any ideas how to do that , thanks preliminarily :)
The first problem is you will want to pull out the groupOp operator.
Then, you have an object and inside that you have an array of objects, so you may want to look at the results of filterArray as that won't have the value you want.
Then, when you loop through, you will want to do it with an index so you can just pull the values out in order.
You may want to look at this question to see how you can get data out of the array:
json decode in php
And here is another question that may be helpful for you:
How to decode a JSON String with several objects in PHP?
There is an answer with an implementation for the server-side php code here
Correction: I had to unescape double-quotes in the 'filters' parameter to get it working:
$filters = str_replace('\"','"' ,$_POST['filters']);