Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and Write PHP Array in MYSQL

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.

like image 1000
user794624 Avatar asked Dec 05 '25 22:12

user794624


1 Answers

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.

like image 129
Ben Lee Avatar answered Dec 07 '25 16:12

Ben Lee