0

Is it possible to store an associative array as it is in the db?

array(
       key  => value,
       key2 => value2,
       key3 => value3,
       ...
      )

Currently, if I write fieldname = '$array', only the string "Array" is stored in the field.

Adil Abbas
  • 63
  • 2
  • 9

4 Answers4

0

Try this

fieldname = json_encode($array);

and when you want to retrieve from database then use

$array = json_decode($fieldname);
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
0

You can also do this:

serialize($array);

and then when you fetch it from the database:

unserialize($array);
Jonan
  • 2,485
  • 3
  • 24
  • 42
0

Do use

$fieldname = json_encode($array);
Torrezzzz
  • 307
  • 2
  • 13
0
    php code to store array in database
    <?
        $array_string = array(key => value, key2 => value2, key3 => value3);
        $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);
        }
    ?>
Chirag Shah
  • 1,463
  • 2
  • 18
  • 40