How to store array in mysql?

This is one of the mostly 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_select_db("mysql_db",$conn);
$array_string=mysql_escape_string(serialize($array));
mysql_query("insert into table (column) values($array_string)",$conn);
?>

To retrieve array from database

<?
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db("mysql_db",$conn);
$q=mysql_query("select column from table",$conn);
while($rs=mysql_fetch_assoc($q))
{
$array= unserialize($rs['column']);
print_r($array);
}
?>

Published on March 15, 2013 by Sunny Verma

Liked It? Get Free updates in your Email

Delivered by feedburner