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.

5
  • you will need to flatten it serialize could work or some encode / decode method
    – Anigel
    Jul 15 2014 at 8:25
  • @kevinabelita. the array keys are not the same as the fields in db table.
    – Adil Abbas
    Jul 15 2014 at 8:28
  • this might give some perspective, this does not cover database insertion though, please avoid mysql_ Jul 15 2014 at 8:29
  • @Anigel, json encoding / decoding will just do fine. Thankyou for the suggestion.
    – Adil Abbas
    Jul 15 2014 at 8:35
  • yes! in my case, json encode / decode is the way indeed! Thanks @kevinabelita
    – Adil Abbas
    Jul 15 2014 at 8:39
0

Try this

fieldname = json_encode($array);

and when you want to retrieve from database then use

$array = json_decode($fieldname);
1
  • this is in fact solved it! My bad, I was not thinking that way. Thanks!
    – Adil Abbas
    Jul 15 2014 at 8:36
0

You can also do this:

serialize($array);

and then when you fetch it from the database:

unserialize($array);
0
0

Do use

$fieldname = json_encode($array);
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);
        }
    ?>
1
  • 1
    Thank you for this solution. It is other way than using json encode / decode.
    – Adil Abbas
    Jul 15 2014 at 9:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.