I have an array what I encode as json and I save it to database. The array looks like
$myarray = array(
'test'=>array('key1'=>'1',
'key2'=>'2',
'key3'=>'3'),
'test2' =>array('key4'=>'1',
'key5'=>'<a href="myclass"></a>'
)
);
json_encode($myarray);
the saved json in my database looks like
{
"test": {"key1":"1",
"key2":"2",
"key3":"3"
},
"test2": {"key4":"1",
"key5":"<a href ="myclass"></a>"
}
}
MYSQL save $sql = "UPDATE my_table SET params= '".json_encode($param )."' WHERE id
='".$key."'";
Than when I retrieve the json string from database and trying to rebuild the array with json_decode($json, true);
outputs null
You could serialize the data rather than storing it as json.
$sql = "UPDATE table SET field='".serialize($myarray)."' WHERE ...";
Then when you want to recreate the array, just pull it out of the table and unserialize() it. It's not human readable in the database; however this technique is fast and works well for storing arrays in the db. If the data is needed by your js scripts then json_encode() it after you unserialize() it.
Have you tryed to use addslashes()
and stripslashes()
php functions ?
Try: To update your table:
$sql = "UPDATE my_table SET params='".addslashes(json_encode($myarray))."' WHERE id ='".$key."';";
to read from table:
$sql = "SELECT params FROM my_table WHERE id='".$key."';";
...code to read row...
$myparams = stripslashes($row['params']);
also you can try the a custom function for a multidimensional array from php manual called stripslashes_deep()
see http://www.php.net/manual/en/function.stripslashes.php (EXAMPLE #2)
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
print_r($array);
// Output
Array
(
[0] => f'oo
[1] => b'ar
[2] => Array
(
[0] => fo'o
[1] => b'ar
)
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.