php - Decode Json data Array and insert in to mysql -
this question may asked here tried search couldn't find have json data 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 extract these using php , inserted mysql db. not work me beginner in coding please solve this
below tried
$jsondata = file_get_contents($jsonfile); $data = json_decode($jsondata, true); echo $data['name']; echo $data['citycode']; $db->save($data, "tablename"); // found php app insert json db
there problems in php code. code $data = json_decode($jsondata, true);
indeed convert json data php array. if need extract datas need insert table, need like
$array_data = $data['cityinfo'];
now $array_data
contains array of data needs inserted tables.you can continue
$db->save($array_data, "tablename");
or manually insert each row using php mysqli
, foreach
loop like
$conn = new mysqli($servername, $username, $password, $dbname); foreach ($array_data $row) { $sql = "insert 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 $row) { $sql = "insert cityinfo (citycode, name) values ('" . $row["citycode"] . "', '" . $row["name"] . "')"; $conn->query($sql); } $conn->close(); ?>
Comments
Post a Comment