I'm saving an array to the db but when I do the array is getting quotes around it from the start to end
e.g
"[{"id":"1","country":"New Zealand","shipping_rate":"1"},{"id":"2","country":"Australia","shipping_rate":"2"}]"
the array shouldn't be quoted at the start and the end when saving but this is happening. When I check my model on the shipping field that is an array I tried to trim it but it's says it can't because it says it's an array, so the problem is when it's being saved to the db for that field
The array should just look like this when being saved unquoted
[{"id":"1","country":"New Zealand","shipping_rate":"1"},{"id":"2","country":"Australia","shipping_rate":"2"}]
mysql doesn't save arrays, it saves strings. When saving an array it is by design that it serializes the array into a string.
If you are using MySql 5.7.8 or later you can use the JSON data type.
https://dev.mysql.com/doc/refman/5.7/en/json.html
You can't save an array in the mysql directly it will throws exception, you should convert it in a string(use json_encode()) and save it in mysql in either varachar/text type field.
Again when you get the data from db, convert it in an array(use json_decode()) and then use it.
u must convert json string to array :
<?php
$json_string= '[{"id":"1","country":"New Zealand","shipping_rate":"1"},{"id":"2","country":"Australia","shipping_rate":"2"}]';
$array = json_decode($json_string,true);
?>
then make a loop with foreach and enter a query in foreach :
<?php
foreach($array as $data){
$id = $data['id'];
$country = $data['country'];
$save= mysql_query("insert into your_database values("$id", "$country")";
}
?>
i home this help
Related
I am storing data in json format in mysql database table column like
table A
column-user_details
"{\"name\":\"sadasfsf\",\"phone\":\"7896521747\",\"address_1\":\"dvgsdsd\",\"state_name\":\"g\",\"city_name\":\"sdgds\",\"zip_code\":\"ghdfh\"}"
I am fetching data like
json_decode($variable, true);
<?php echo $variable['name'];?>
However I am getting error like
Illegal string offset 'name'
the first parameter of json_decode is not a parameter passing by reference, so if you want to get the json code as php array, you mast adding the result of json_decode into a variable.
<?php
$variable = "{\"name\":\"sadasfsf\",\"phone\":\"7896521747\",\"address_1\":\"dvgsdsd\",\"state_name\":\"g\",\"city_name\":\"sdgds\",\"zip_code\":\"ghdfh\"}";
$array = json_decode($variable, true);
echo $array['name'];
NB: json_decode() is a php code, so you must use it after <?php tag, not outside of it
how to store array values in the single field database using json_encode in luman?
I get value from the request:
$qualification_id = array($request->input('qualification_id'));
my json encode line:
$serializedArr=json_encode( $qualification_id);
my insert query:
$result = DB::insert("insert into `borrower_registration`
(first_name,middle_name,last_name,city_id,
state_id,dob,marital_id,father_husband,
institute,qualification_id,graduated_id)
values ('$first_name',' $middle_name','$last_name','$city_id',
'$state_id ','$dob ',' $marital_id','$father_husband',
'$institute','$serializedArr','$graduated_id')");
I given sample input for the array 1,2,3,4 and using
print_r($qualification_id)
and get output like [1,2,3,4]
data type of the column qualification_id is int
I execute the code and it store in database as 0 .please give valuable suggestions.
Check if qualification_id column has JSON or TEXT format.
Confusing title, the basics are that I'm saving a fully sorted and ordered multidimensional array from a script and into MySQL. I then, on another page, pull it from the database and unserialize it, and then proceed to print it out with this,
$s = "SELECT * FROM gator_historical_data WHERE channelid = '{$chanid}'";
$r = $link->query($s);
$comboarray = array();
while ($row = mysqli_fetch_assoc($r)) {
$comboarray[] = unserialize($row['dataarray']);
}
foreach ($comboarray as $item) {
$desc = $item['content']['description'];
$title = $item['content']['title'];
$datetime = $item['datetime'];
// ... ^^^ problems getting array data
}
The problem is that it doesn't take the full array from MySQL, only the first entry and thus only prints the first 'array'. So where the returned value from dataarray looks like this (var_dump): http://pastebin.com/raw.php?i=Z0jy55sM the data stored into the unserialized $comboarray only looks like this (var_dump): http://pastebin.com/raw.php?i=Ycwwa924
TL;DR: Pulling a serialized multidimensional array from a database, unserializing and it loses all arrays after the first one.
Any ideas what to do?
The string you've got is a serialized string plus something more at the end that is also a serialized string again and again:
a:3:{s:6:"source";s:25:"World news | The Guardian";s:8:"datetime ...
... story01.htm";}}a:3:{s:6:"source";s:16:"BBC News - World";
^^^
This format is not supported by PHP unserialize, it will only unserialize the first chunk and drop everything at the end.
Instead create one array, serialize it and store that result into the database.
Alternatively you can try to recover for the moment by un-chunking the string, however in case the paste was done right, there are more issues. But on the other hand the paste obvious isn't the done fully correct.
Hi I'm trying to insert the json array into my MySQL database.With array json data from android client.
[{"name":"peter","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"111","phone":"222","city":"hn","email":"1#yahoo.com"}]
If you want to store the array as a string, you can use JSON.stringify():
$string = [{"name":"peter","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"111","phone":"222","city":"hn","email":"1#yahoo.com"}];
$json = JSON.stringify($string);
The variable $json is then a simple string which can be inserted into MySQL easily.
You can then use:
var obj = JSON.parse($json);
To convert the string back to an array.
This method usually isn't recommended for performance reasons though, so you might alternatively want to break up the array and store each field individually.
Try this:
$json = serialize(json_array);
Use $jsonArray = json_decode($jsonStr);.
Then iterate the array as you want to save data in your mysql database.
you can use - serialize()
$json = '[{"name":"peter","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"111","phone":"222","city":"hn","email":"1#yahoo.com"}]';
$newJson = serialize(json_decode($json));
$newJson is ready to be inserted. and after fetching -
$data = unserialize($fetchedData); and then json_encode($data);
The array in the database is stored as a serialized string, such as this:
a:1:{i:0;a:4:{s:8:"category";s:26:"Category Name";s:4:"date";s:0:"";s:8:"citation";s:617:"617 Char Length String (shortened on purpose)";s:4:"link";s:0:"";}}
It's structure should resemble the following when unseralized:
array {
id => array { category => Value, date => Value, citation => Value, link => Value }
}
The php code I'm using is:
$prevPubs = unserialize($result[0]['citations']);
The $result[0]['citations'] is the serialized string. $prevPubs will return false. Which indicates an error if I'm not mistaken.
Any help would be greatly appreciated.
b:0 is boolean:false in serialized format. Unserialize would NOT return that exact string, it'd just return an actual boolean FALSE. This means that whatever you're passing into the unserialize call is not a valid serialized string. Most likely it's been corrupted somehow, causing the unserialize call to fail.
in order to handle serialized multidmensional arrays and mysql use this:
<?php
//to safely serialize
$safe_string_to_store = base64_encode(serialize($multidimensional_array));
//to unserialize...
$array_restored_from_db = unserialize(base64_decode($encoded_serialized_string));
?>
i'm pretty sure serialized string in your database is corrupted
You have to unserialize the whole string
$result = unserialize($serialized);
and then use the $result[0]['citation'] index of the result array.