ONYX
ONYX

Reputation: 5859

saving array to db but is serialized as a string

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"}]

Upvotes: 0

Views: 94

Answers (3)

Sate Wedos
Sate Wedos

Reputation: 589

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

Upvotes: 0

RAUSHAN KUMAR
RAUSHAN KUMAR

Reputation: 6006

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.

Upvotes: 1

Luke
Luke

Reputation: 640

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

Upvotes: 5

Related Questions