I want to save a PHP associative array from a PHP varible to a MYSQL database, then later access the stored value (within the MYSQL database) and use it within PHP as an associative array.
$arr = array("abc"=>"ss","aaa"=>"ddd");
now i want to save
array("abc"=>"ss","aaa"=>"ddd");
to the database and again want to retrive it and assign it to variable.
I tried to use the serialize function, but it only saved the word "Array" into database.
One way to do this is to serialize it into a string before insert, and then deserialize it into array after fetching. There are different ways to do that, but if your arrays are simple, JSON is an acceptable serialization format.
You could json_encode on the way in:
$str = json_encode($arr);
// Insert $str into db
Then json_decode later:
// Got $str from db
$arr = json_decode($str);
Another method is serialize:
$str = serialize($arr);
// Insert $str into db
And unserialize:
// Got $str from db
$arr = unserialize($str);
This will allow more possibilities for what you can serialize than json_encode and json_decode, but it will be harder to inspect the database manually to see what's in there.
So both methods have advantages and disadvantages. There are other serialization/marshal formats out there too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With