Sunday, 15 September 2013

How to store array in mysql?

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

1
2
3
4
5
6
7
<?
$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

1
2
3
4
5
6
7
8
9
10
<?
$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);
}
?>

1 comment:

  1. Nice blog...Very useful information is providing by ur blog..here is a way to find.
    Hire PHP Mysql Developers in India

    ReplyDelete