Skip navigation

Although I’m sure many people already knew the answer to this, I wanted to post the solution mainly so that I don’t forget.  I spent about 30 mins looking for the answer again yesterday since I had forgotten it from the last time I used it. 

To store an array (even a multi-dimensional array) from PHP into MySQL, use the serialize() and unserialize() functions.  There’s other ways of doing it I’m sure, but this has proven quick and painless for myself.  So, sample code might be:

//To insert
$SampleArray = array();
$SampleArray = serialize($SampleArray);

$sql = “INSERT INTO table (‘ArrayField’) VALUES (‘$SampleArray’);
//Run sql statement

//To retrieve
$SampleArray = unserialize($row_table[‘ArrayField’]);

Advertisements

5 Comments

  1. How will a multidimensional array be stored? Can you give an example?

    • Sure. According to the PHP Manual:

      serialize() creates a byte-stream representation of value that can be stored anywhere

      A serialized Multi-dimensional associative array of:

      Array ( [0] => Array ( [Start] => 1234 [End] => 5678 [Total] => 14 ) )

      Generates:

      a:2:{i:0;a:3:{s:5:”Start”;i:1234;s:3:”End”;i:5678;s:5:”Total”;i:14;}}

      Which can then be easily inserted into MySQL. Does that help?

  2. I understand what serzalized do, I dont understand how SQL read this, first I thought this statment should be an UPDATE, than Key And Value makes Sence.
    What you mean ist that a multi-dimensional array puts more rows!
    Like:
    Array ( [0] => Array ( [Start] => 1234 [End] => 5678 [Total] => 14 )
    [1] => Array ( [Start] => 124 [End] => 568 [Total] => 4 ) )
    effect 2 rows.
    But yesterday I thought only it effects only 1 row , that would be strange.
    By the way, is it possible to do the same for an UPDATE? I think not, but… world is so big und unexpacted

    • We might be talking about two different things. I’m taking an array and storing the entire array within a single field in my table. It looks like you are wanting to parse through an array and insert the data into multiple fields/rows? Would that be correct? If so, you wouldn’t have to use serialize(), you can just run a foreach loop and run the inserts or updates inside that.

  3. Oh, jes, now I see your Point, you just take an Array and put it in one Field. -.-

    I thought SQL read it as one row… kind of stupid :S,

    Thank you


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: