Last updated on August 29th, 2020 at 01:31 am
We will see how we can store PHP array in database. We will store the php array in database and we get it back, as PHP array.
When we create management systems or applications such as CMS, we need to store a lot of configurations per user, per module etc. Multidimensional array is the best ever thing to work with in such situations. Configurations can be of two different types; searchable and non-searchable.
Searchable configurations are those which we use to filter a search result. For example various flags, tags, categories etc. that we store with contents. We might need to filter contents with this flags, tags etc. Non-searchable configurations are like widget settings. We do not search for settings of an widget, rather we need those settings while rendering the widget.
Here we will see how we can store a multidimensional PHP array (settings or configuration) in MySQL database. Our task is to store the array in the database and while we get it back, we get it like an array again. PHP provides two pair of methods for this.
Method 1: Serialize and Unserialize
Consider we have the following array of settings that we need to store into database
$settings = array( 'id' => 'mydemoWidget', 'status' => 'active', 'configuration' => array( 'title' => 'Demo Title', 'style' => array( 'background-color' => '#fff', 'border' => true, ), 'content' => array( 'category' => null, 'page' => 5, 'tags' => array(5,4,3), 'start' => 0, 'total' => 10 ), ) );
Then we simple call the
serialize() function as follows
$serialized_settings = serialize($settings);
The serialized array will look like following
Now as it is just a string, you can store this string in an
TEXT field in your MySQL Database as usual.
When you query the table to get the settings back, you get the above serialized string. Now you just simply call the
unserialize() function to get your array back from the serialized string. You send the serialized string as the only parameter of the
$settings = unserialize($serialized_settings);
Method 2: JSON Encode and Decode
json_encode() function is called to convert a PHP array to a string in this case as follows. The above mentioned array has been used here again.
$serialized_settings = json_encode($settings);
The array will now become a string as follows
You can store this string in a
TEXT field in MySQL database as usual.
After querying the data back to PHP, simply call the
json_decode() function with first parameter being the JSON encoded string you pulled from DB, and
TRUE as the second parameter as it will force the function to output an array instead of an Standard Object.
$settings = json_decode($serialized_settings, true);
Okay, so that’s it.
I choose JSON Encode & Decode as I found it faster than serializing.