Back To Normal
Click Here To Subscribe Via Email

Subscribe To Our E-Mail Newsletter

Sunday, January 4, 2015

Store Arrays to MySQL with PHP


Couch ModePrint It


This is a simple yet one of the most asked questions that many developers have in their mind. Storing arrays to MySQL should be done only in a very few cases. You should better save your array values in appropriate columns, you should have a good table structure.

However, while it is needed to store whole arrays to MySQL columns in some cases, how you should do it?


There are two best ways to store arrays to MySQL (or wherever you want) with PHP's native serialize()/unserialize() and json_encode()/json_decode() functions.


Storing as a JSON string


Suppose that you want to store the array ($array). You will need to convert the array to the JSON string first using json_encode() and then you can store it to wherever you want (e.g. MySQL column). You can retrieve the array from json string using json_decode().

$array=array("hello", "php", "world");

$json_string=json_encode($array);

/* handle $json_string here / store wherever you want */



Retrieving array from JSON string


//get $json_string back from wherever you stored

//decode the json string (convert back to array)
$decoded_json=json_decode($json_string, true);


/* print array to screen / handle array here */
print_r($decoded_json);





Storing as a serialized string


There is another way of storing array other than json method. You can store the array as a serialized string using PHP's serialize() function. To retrieve back, you can make use of the unserialize() function.

$array=array("hello", "php", "world");

$serialized=serialize($array);

/* handle $serialized here / store wherever you want */



Retrieving array from a serialized string


//get $serialized back from wherever you stored

//unserialize (convert back to array)
$unserialized=unserialize($serialized);


/* print array to screen / handle array here */
print_r($unserialized);




You can see the code demo here.


How would you like to handle and store arrays?


:D
:)
:[
;)
:D
:O
(6)
(A)
:'(
:|
:o)
8)
(K)
(M)