Wednesday, 20 January 2016

Pooling JSON data into MySql Table sequentially!

We have JSON data :

[{
"timeMillis": 1452502968583,
"latitude": -33.9041,
"longitude": 170.7297,
"current": 15.7,
"direction": "GROUND"
}, {
"timeMillis": 1452506410228,
"latitude": -33.6113,
"longitude": 172.1532,
"current": 8.1,
"direction": "GROUND"
}, {
"timeMillis": 1452513792306,
"latitude": -48.9861,
"longitude": 169.7887,
"current": -38.5,
"direction": "GROUND"
}]

save it as file.json

Now use this :

<?php
    $con = mysqli_connect("localhost","root","","lightning");

    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

    $jdata = file_get_contents("/home/file.json");
    
    $data = json_decode($jdata, true);
    foreach($data as $mydata)
    {
        $sql = "INSERT INTO data(timeMillis, latitude, longitude, current) VALUES (".$mydata['timeMillis'].",".$mydata['latitude'].",".$mydata['longitude'].",".$mydata['current'].")";   
        if(!mysqli_query($con, $sql))
        {
            die('Error : ' . mysql_error());
        }
    }

    mysqli_close($con);
    //echo "Le bhai, ho gaya tera data store!"         
?>

Job Done!

No comments:

Post a Comment