3

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
1
  • 1
    Can you post what you've tried so far? Commented Nov 5, 2016 at 19:28

1 Answer 1

9

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();
?>
Sign up to request clarification or add additional context in comments.

3 Comments

Nice Explanation Kiran! Thanks
Glad to know :)
How do I change it to SELECT rather than INSERT?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.