Reading and writing PHP array in MYSQL

I want to store a PHP associative array from var to a MYSQL database and then access the stored value (in a MYSQL database) and use it in PHP as an associative array.

$arr = array("abc"=>"ss","aaa"=>"ddd");


now i want to save



to the database and want to retrieve it again and assign it to a variable.

I tried to use the function serialize

, but only saved the word "Array" in the database.


source to share

2 answers

One way to do this is to serialize it to a string before inserting, and then deserialize it to an array after retrieving. There are different ways to do this, but if your arrays are simple, JSON is an acceptable serialization format.

You can json_encode along the path to:

$str = json_encode($arr);
// Insert $str into db


Then json_decode later:

// Got $str from db
$arr = json_decode($str);


Another serialize method :

$str = serialize($arr);
// Insert $str into db


And unserialize :

// Got $str from db
$arr = unserialize($str);


This will allow more room for what you can serialize than json_encode and json_decode, but it will be more difficult to manually check the database to see what's in there.

Thus, both methods have advantages and disadvantages. There are other serialization / marshal formats as well.



As Ben said, you need to serialize your array before you store it in the database, and then unserialize it when you read it. If "Array" is being written to your database, you probably are not storing the serialize () results for the variable you are writing.


function store()
    $arr = array("abc"=>"ss","aaa"=>"ddd");

    $serialized = serialize($arr);

    // Store $serialized to the database

function retrieve()
    // Retrieve $serialized from the database

    $arr = unserialize($serialized);




All Articles