How to store array in mysql?

This is one of the most asked question by php programmer because mysql doesn’t has any array data type. So we can not store array directly into mysql database.

To do this we have to first convert array into string using php serialize() function then save it into mysql database.

php code to store array in database

$array = array("foo", "bar", "hello", "world");
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_query("insert into table (column) values($array_string)",$conn);

To retrieve array from database

$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
$q=mysql_query("select column from table",$conn);
$array= unserialize($rs['column']);

One thought on “How to store array in mysql?

  1. Abbas Haroon

    Thanks for sharing. I totally forgot the serialize() function. I was working in codeignitor and now i remebered that it had a built in mysql function which auto serilize. thanks a lot. Keep posting


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>