How to Store Multi-dimensional Array in Mysql Using PHP. There are more number of doubts will arise, when you working with multi dimensional array and database operations together. Always the multi dimensional array is little complicated one. So here is my simple tutorial to understand it better, and work easily, You have two options to save datas inMySQL Table.
Let’s discuss each one separately, and we will start from json_encode() function.
This is one a good method, while playing with AJAX and PHP. Because now a days, AJAX is most popular one and needs to retrieve the results on the same page by processing the AJAX calls. Let’s start with an simple example. I dont code the database connections codes, just go with mysql query and how to apply the json functions.
$default_array = array('a' => 1, 'd' => 4,'c' => 3, 'b' => 2, 'e' => 5);
Here you can print the array and json encoded string for your understanding,
print_r($default_array); echo json_encode(default_array);
Here, you can’t save the array directly to the database table. But json_encoded string can be stored easily. Liekwise, you can encode the multi dimensional array as string and store it in mySQL table. While reteriving the string has to be decoded again and comes to normal array again, Here is an example
Another Method is Serialize function.
This is also one a simple function to prepare array items as string. The serialize() function will be like the json encoding. But there is some difference in encoded string. Its php functions.So you can use it inside the PHP and you can’t use it on AJAX like the json functions. But good to work with php. you can use the unserialize() function to get the original array back
echo serialize($default_array); unserialize($encoded_array);