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

4
  • 1
    you need to use json to store array data in mysql Commented Nov 16, 2016 at 9:04
  • please.. can you tell me how to do this Commented Nov 16, 2016 at 9:05
  • 1
    You should have a look at serialize Commented Nov 16, 2016 at 9:18
  • Funny, if I Google that title of yours I see this. Please tell me, how were you unable to find this? Commented Nov 17, 2016 at 2:14

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

can i store directly $result = json_encode($array); like this
you need to store $result data/output in database
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

2 Comments

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";}
I'm not sure what you mean but you can save that serialized string to the database
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.