Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store and retrieve a multidimensional array using php and mysql

I have a multidimensional array in PHP like this:

$array = array(
    "Part1" => array(
        "Subpart1" => array(0, 1),
        "Subpart2" => array(1, 0)
    ),
    "Part2" => array(0),
    "Part3" => array(0, 1, 0)
);

Now I want to store this array in a MySQL table and retrieve it exactly like this again on another PHP page.

I've been trying using serialize() and unserialize()

$array= serialize($array);

and then on the other page

$array= $row['Array'];
$array2 = array();
$array2 = unserialize($array);

But I seem to do something wrong, in the beginning I got a var_dump of bool(false) and now I get a var_dump of NULL.

like image 501
Pmarcoen Avatar asked May 21 '09 15:05

Pmarcoen


2 Answers

Use column type TEXT. Serialized data often doesn't fit VARCHAR(255).

like image 155
Jet Avatar answered Oct 07 '22 21:10

Jet


Your code looks ok...

One thing that can catch you out is if your column is too small - if you use VARCHAR(255) your data can be truncated and won't unserialize. If you add the value of $row['Array'] I could see if it's whole.

like image 22
Greg Avatar answered Oct 07 '22 21:10

Greg