Feroza Feroza - 1 month ago 7
JSON Question

Decode Json data Array and insert in to mysql

This question already may asked here but i tried search couldn't find it
I have Json data like below

{"CityInfo":[{"CityCode":"5599","Name":"DRUSKININKAI"},{"CityCode":"2003","Name":"KAUNAS"},{"CityCode":"2573","Name":"KLAIPEDA"},{"CityCode":"1692","Name":"VILNIUS"}],"StartTime":"2016-11-05 07:20:34","EndTime":"2016-11-05 07:20:34"}


i tried to extract these using php and inserted to mysql db. but its not work for me as i beginner in coding please help to solve this

Below I tried

$jsondata = file_get_contents($jsonFile);
$data = json_decode($jsondata, true);
echo $data['Name'];
echo $data['CityCode'];
$db->save($data, "tableName"); // i found a php app to insert json to db

Answer

There are some problems in your php code. The code $data = json_decode($jsondata, true); indeed convert your json data into PHP array. But if you need to extract the datas that you need to insert into your table, then you need to do like

$array_data = $data['CityInfo'];

Now this $array_data contains the array of data that needs to be inserted into your tables.You can continue with

$db->save($array_data, "tableName");

or you could manually insert each row using a PHP MySQLi and forEach loop like

$conn = new mysqli($servername, $username, $password, $dbname);

foreach ($array_data as $row) {
    $sql = "INSERT INTO cityinfo (CityCode, Name) VALUES ('" . $row["CityCode"] . "', '" . $row["Name"] . "')";
    $conn->query($sql);
}

Full example

<?php

$jsonFile="CityInfo.json";
$jsondata = file_get_contents($jsonFile);
$data = json_decode($jsondata, true);

$array_data = $data['CityInfo'];

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "yourDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

foreach ($array_data as $row) {
    $sql = "INSERT INTO cityinfo (CityCode, Name) VALUES ('" . $row["CityCode"] . "', '" . $row["Name"] . "')";
    $conn->query($sql);
}

$conn->close();
?>