Prashant Kumbhar
Prashant Kumbhar

Reputation: 59

How to Store Array in Mysql Using PHP

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

Upvotes: 1

Views: 4896

Answers (3)

Shyam
Shyam

Reputation: 300

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

Upvotes: 0

RJParikh
RJParikh

Reputation: 4166

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

Upvotes: 5

jurruh
jurruh

Reputation: 119

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

Upvotes: 4

Related Questions