3

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.

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

6 Comments

that is good solution but i need else than json_encoding ... i need to use that array in PHP so can't save it as json
i need to use it at many places so required some thing better. hope you can understand why i need it. i think it should be some thing like convert array to string and then back string to array. like json did but i need else than json
@user794624, see my update. There is also serialize and unserialize.
i use serialize function but whats going to database is a word "Array" instead of content of array. my database type is mediumtext
@user794624, then the problem is with some other part of your code, because serialize/unserialize definitely work. Please post your code that uses these methods, maybe there's a bug there.
|
1

As Ben said, you need to serialize your array before storing it in the database then unserialize it when you read it back. If 'Array' is being written to your database then you are probably not saving the results of serialize() to the variable that you are writing.

<?php

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.