1

I want to store array in mysql database. with key and value

Following are code i used

         $name= "prashant";
         $lname= "kumbhar";
         $test = "testing";

        $array = array('fname'=>$name,'lname'=>$lname,'test' =>$testing);

Store these $array in database using php

Shyam
  • 280
  • 1
  • 6
  • 17

3 Answers3

5

Use json_encode() to store data in mysql table.

<?php
$name= "prashant";
$lname= "kumbhar";
$test = "testing";

$array = array('fname'=>$name,
               'lname'=>$lname,
               'test' => $test
         );

$res = json_encode($array);
echo "Convert from array to json :" .$res;

echo "\n\nFrom json to array:\n";
print_r(json_decode($res));

output

Convert from array to json :
{"fname":"prashant","lname":"kumbhar","test":"testing"}

From json to array:
stdClass Object
(
    [fname] => prashant
    [lname] => kumbhar
    [test] => testing
)

At the time of retrieve data in array form then use json_decode()

Working Demo : Click Here

RJParikh
  • 4,096
  • 1
  • 19
  • 36
4

You can serialize the array and store the string in the database:

serialize ($array);

If you want to use it just unserialize the result that you've get from the database

$array = unserialize ($databaseResult);

If you prefer json you can do the same with json_encode and json_decode

jurruh
  • 119
  • 6
  • when i use serialize array then data goes 0 and user unserialize then data store a:15:{s:18:"electricity_backup";s:18:"electricity backup";s:15:"air_conditioned";s:15:"air conditioned";s:22:"djcredit_card_accepted";} – Prashant Kumbhar Nov 16 '16 at 09:14
  • I'm not sure what you mean but you can save that serialized string to the database – jurruh Nov 16 '16 at 09:18
0

use convert array into json format using json_encode and then store in database, you can convert json string format back to array using json_decode. Example

  $name= "prashant";
  $lname= "kumbhar";
  $test = "testing";

  $array = array('fname'=>$name,'lname'=>$lname,'test' = $testing);
  $data_for_db = json_endcode($array);

You can convert stored json format data back to normal array as below

$array = json_decode($data_for_db);

Thanks

Shyam
  • 280
  • 1
  • 6
  • 17