Rangga Leo
Rangga Leo

Reputation: 72

how to storing json data to mysql with php

This is my example json data

[
    {"kode":"AX5","harga":"6200","status":"1","nama":"AXIS 5"},
    {"kode":"AX10","harga":"11250","status":"1","nama":"AXIS 10"},
    {"kode":"AX25","harga":"25750","status":"1","nama":"AXIS 25"},
    {"kode":"AX50","harga":"50800","status":"1","nama":"AXIS 50"}
]

and i want to save the data to mysql with php, field product_id, price, status, name, anyone can help me please

my problem is, i dont know better code for me in php

Upvotes: 0

Views: 107

Answers (2)

Shafiqul Islam
Shafiqul Islam

Reputation: 5690

you can use json_decode(). it takes a JSON encoded string and converts it into a PHP variable.

  <?php
$json_data = '[{"kode":"AX5","harga":"6200","status":"1","nama":"AXIS 5"},{"kode":"AX10","harga":"11250","status":"1","nama":"AXIS 10"},{"kode":"AX25","harga":"25750","status":"1","nama":"AXIS 25"},{"kode":"AX50","harga":"50800","status":"1","nama":"AXIS 50"}]';
$array_data = json_decode($json_data);
echo '<pre>';
print_r($array_data);

foreach ($array_data as $event) {
    echo 'Product_id:' . $event->kode;
    echo "<br>";
    echo 'status:' . $event->status;
    echo "<br>";
}

then output is

Array
(
    [0] => stdClass Object
        (
            [kode] => AX5
            [harga] => 6200
            [status] => 1
            [nama] => AXIS 5
        )

    [1] => stdClass Object
        (
            [kode] => AX10
            [harga] => 11250
            [status] => 1
            [nama] => AXIS 10
        )

    [2] => stdClass Object
        (
            [kode] => AX25
            [harga] => 25750
            [status] => 1
            [nama] => AXIS 25
        )

    [3] => stdClass Object
        (
            [kode] => AX50
            [harga] => 50800
            [status] => 1
            [nama] => AXIS 50
        )

)

Product_id:AX5
status:1
Product_id:AX10
status:1
Product_id:AX25
status:1
Product_id:AX50
status:1

for more information

http://php.net/manual/en/function.json-decode.php

Upvotes: 1

Nikko Madrelijos
Nikko Madrelijos

Reputation: 545

You could use PHP

json_decode()

function to convert that json string into PHP variables.

You could then get those values and save them to the MySQL Database;

Source json_decode PHP Manual

Upvotes: 3

Related Questions