How to store array in MySQL
Today I got a question from a person that How to store array in mysql using php. So now I’m going to share the solution for storing array in mysql as if that person don’t know the solution then there will be many people may be also facing the problem.
We can not store Array in mysql directly.First, we have to convert array into string using php serialize function and then save it in our mysql database.
Connect to MySQL
First of all we need to connect to MySQL to store the data.
Create a file with a name config.php and the below php code to connect to mysql.
<?php
$con = mysqli_connect("localhost","mysql_username","mysql_password","database_name");
?>
Convert Array into String
Now we have to convert our array into string and for that we will php serialize function.
<?php
$array = array("Name"=>"Shubham","Age"=>"17","website"=>"http://mycodingtricks.com");
$string_array = serialize($array);
echo $string_array;
?>
It’s output will be : a:3:{s:4:"Name";s:7:"Shubham";s:3:"Age";s:2:"17";s:7:"website";s:25:"http://mycodingtricks.com";}
Save Array data in MySQL
Now after converting array into string we will save it in out mysql database using mysqli_query function.
<?php
include 'config.php';
$array = array("Name"=>"Shubham","Age"=>"17","website"=>"http://mycodingtricks.com");
$serialize = serialize($array);
mysqli_query($con,"INSERT into `table_name` (`column`) VALUES ('$serialize')");
?>
Retrieving data from MySQL
<?php
include 'config.php';
$data = mysqli_query($con,"SELECT column FROM table_name");
while($result=mysqli_fetch_array($data))
{
$array= unserialize($result['column']);
print_r($array);
}
?>
In the above code we have used unserialize php function to convert the string into array.
I hope you loved it.



Thank you so much! Just what i was looking for. Very helpful 🙂
Hi Shane,
Glad you liked it. Would love to hear more from you in future.
Best Regards,
Shubham