A get in my PHP script JSON string that looks like this (array with any objects):
[
{
"source":"symbols/2/2.png",
"ypos":133,
"template":"8B82CA47-41D2-D624-D6A2-37177CD82F28",
"rotation":0,
"type":"MyImage",
"width":252,
"depth":5,
"height":159,
"xpos":581
},
{
"source":"symbols/2/2.png",
"ypos":175,
"template":"8B82CA47-41D2-D624-D6A2-37177CD82F28",
"rotation":0,
"type":"MyImage",
"width":258,
"depth":3,
"height":163,
"xpos":214
},
{
"color":"0",
"ypos":468.38,
"fontSize":28,
"xpos":156.95,
"rotation":0,
"type":"MyTextArea",
"width":268.05,
"depth":7,
"height":244.62,
"fontFamily":"Verdana Bold",
"template":"8B82CA47-41D2-D624-D6A2-37177CD82F28"
}
]
How i can save each JSON object in this array with a record in mySQL?
Try this:
<?php
$json = '[
{
"source":"symbols/2/2.png",
"ypos":133,
"template":"8B82CA47-41D2-D624-D6A2-37177CD82F28",
"rotation":0,
"type":"MyImage",
"width":252,
"depth":5,
"height":159,
"xpos":581
},
{
"source":"symbols/2/2.png",
"ypos":175,
"template":"8B82CA47-41D2-D624-D6A2-37177CD82F28",
"rotation":0,
"type":"MyImage",
"width":258,
"depth":3,
"height":163,
"xpos":214
},
{
"color":"0",
"ypos":468.38,
"fontSize":28,
"xpos":156.95,
"rotation":0,
"type":"MyTextArea",
"width":268.05,
"depth":7,
"height":244.62,
"fontFamily":"Verdana Bold",
"template":"8B82CA47-41D2-D624-D6A2-37177CD82F28"
}
]';
//create a DB connection
con = mysql_connect("localhost","username","password");
mysql_connect _db('your_database',$con);
$result = json_decode($json);
foreach($result as $key => $value) {
if($value) {
//how to use json array to insert data in Database
mysql_query("INSERT INTO tablename (source, ypos, template) VALUES ($value->source, $value->ypos,$value->template)");
}
mysql_close($con);
}
Note: But it is recommended to use PHP Data Objects(PDO) to do database operations.
Check here
Use json_decode and then construct a insert statement using the values of the array
Related
I have a json file stored on server & it looks like below:
{
"support_link":"#",
"support_link_2":"#",
"packs":[
{
"identifier":1,
"viewCount":0,
"downloadCount":0
},
{
"identifier":2,
"viewCount":0,
"downloadCount":0
}
]
}
By using PHP, I want to update the viewCount & downloadCount of some of the arrays inside packs.
But the thing is the data is received via a POST method to the server which contains another json with info. of which identifier to update & what param to update, & I am not able to update the existing file & save it back.
Received Json format:
{
"impressions": [
{
"identifier": "1",
"impressionCount": 2
},
{
"identifier": "100",
"impressionCount": 2
},
{
"identifier": "1000",
"impressionCount": 2000
}
],
"downloads": [
{
"identifier": "1",
"downloadCount": 10
}
]
}
What I've tried to do so far:
$json = file_get_contents('php://input');
if ($json != '') {
$properJsonFormatted = json_decode($json, true);
$impressions = $properJsonFormatted['impressions'];
$downloads = $properJsonFormatted['downloads'];
$testConfig =
$json = file_get_contents('php://input');
if ($json != '') {
$properJsonFormatted = json_decode($json, true);
$impressions = $properJsonFormatted['impressions'];
$downloads = $properJsonFormatted['downloads'];
$testConfig = json_decode(file_get_contents("test_config.json"),true);
$packs = $testConfig['packs'];
foreach ($packs as &$pack) {
$packIdentifier = $pack['identifier'];
foreach ($impressions as $impression) {
$impressionIdentifier = $impression['identifier'];
if ($packIdentifier == $impressionIdentifier) {
$pack['viewCount'] += $impression['impressionCount'];
$newCount = $pack['viewCount'];
print("Id: $packIdentifier, ViewCount: $newCount\n");
}
}
}
put_file_contents("test_config.json" , $testConfig);
// print_r($testConfig);
// Save back the updated test_config.json
}
}
UPDATE
Seem to have misinterpreted the question. The actual problem seems to be much simpler.
Change this:
put_file_contents("test_config.json" , $testConfig);
To this:
file_put_contents('test_config.json', json_encode($testConfig));
Also change this:
$packs = $testConfig['packs'];
To this:
$packs = &$testConfig['packs'];
As it seems you forgot to assign that by reference, while you correctly did that in the foreach.
I am struggling with the problem of transferring json-multidimensional array data to SQL.
This is my json file (data.json):
{
"Data 1": {
"Text1": "Anything1",
"Text2": "Anything2"
},
"Data 2": {
"2018-08-02": {
"1.": "145",
"2.": "258"
},
"2018-08-03": {
"1.": "428",
"2.": "528"
},
"2018-08-04": {
"1.": "727",
"2.": "514"
}
}
}
I have a php code:
<?php
$db = new PDO('mysql:host=localhost;dbname=test','root','');
$jsonData = file_get_contents('data.json');
$data = json_decode($jsonData, true);
?>
So now I have a php array $data.
I need to load an array into the following columns in sql: "DATE" (eg "2018-08-02" etc), "1.", "2.".
This is what the final effect in mysql should look like
And I do not know what to do next.
I tried to do as it is shown in this video: https://www.youtube.com/watch?v=4zTjCpBqSbw and ia other websites (https://www.w3schools.com/js/js_json_php.asp), but for me the date (eg "2018-08-02") is a variable and I do not know how to solve the problem in this case.
Here's one way you could do it.
https://3v4l.org/peLqP
BUT you should not be inserting data in this way - this is for illustration only. Use prepared statements or something similar.
<?php
$json = "{
\"Data 1\": {
\"Text1\": \"Anything1\",
\"Text2\": \"Anything2\"
},
\"Data 2\": {
\"2018-08-02\": {
\"1.\": \"145\",
\"2.\": \"258\"
},
\"2018-08-03\": {
\"1.\": \"428\",
\"2.\": \"528\"
},
\"2018-08-04\": {
\"1.\": \"727\",
\"2.\": \"514\"
}
}
}";
$jsonDecoded = json_decode($json, true);
foreach ($jsonDecoded['Data 2'] as $dateKey => $data) {
$values = implode(',', $data);
$statement = "INSERT INTO mytable (TheDate, Value1, Value2) VALUES ('{$dateKey}'," . $values . ");";
echo $statement . PHP_EOL;
}
Output:
INSERT INTO mytable (TheDate, Value1, Value2) VALUES ('2018-08-02',145,258);
INSERT INTO mytable (TheDate, Value1, Value2) VALUES ('2018-08-03',428,528);
INSERT INTO mytable (TheDate, Value1, Value2) VALUES ('2018-08-04',727,514);
My client sent me this JSON so I can loop and save the data in Mysql. I just can not get it because it's different from what I work at;
Can someone give me some hint and what is the difference from one format to another.
Error presented is: Warning: Invalid argument supplied for foreach () in line 28
foreach ($ json_data ['service_devices'] as $ key => $ value) {
Formator EX I've ever worked with:
{
"ordem_de_servico": [
{
"oser_numero_os": 23940493,
"oser_address_name": NAME;
CUSTOMER JSON
ordem_de_servico:
{
"oser_numero_os":23940493,
"oser_dt_abertura":"28/03/2018",
"servico":{
"serv_cod_servico":60,
"serv_descr_servico":"CORTE POR DEBITO"
},
"cliente":{
"clie_ident_cliente":638617,
"nome":"MARIA APARECIDA FERREIRA DO NASCIMENTO"
},
"unidade_consumidora":{
"unid_ident_uc":2436434,
"logr_nome_logr_expandido":"R JOSE GUIMARAES"
},
"faturas":[
{
"total_fatura":"88.44",
"ftcd_mes_ano_fatmto":"2017-04-01"
},
{
"total_fatura":"45.16",
"ftcd_mes_ano_fatmto":"2017-03-01"
}
]
}
My last attempt
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webservice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Read JSON file
$json = file_get_contents('oss.json');
//Decode JSON
$json_data = json_decode($json,true);
foreach($json_data['ordens_de_servico'] as $key => $value){
$os = $value["oser_numero_os"];
$data_abertura = $value["oser_dt_abertura"];
foreach($json_data['ordens_de_servico'][$key]['faturas'] as $index => $row){
$valorParcelas = $row["total_fatura"];
$sql = "SELECT numero_os FROM os WHERE numero_os = '$os'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "PULAR FATURA"."<p>";
}else {
$sql = "INSERT INTO faturas (valorParcelas, numero_os) VALUES ('$valorParcelas', '$os')";
if ($conn->query($sql) === TRUE) {
echo "<strong>".$valorParcelas." - FATURA OK"."</strong>"."<p>";
} else {
echo "Error Fatura";
}
}
}
$sql = "SELECT numero_os FROM os WHERE numero_os = '$os'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "PULAR"."<p>";
}
else{
$sql = "INSERT INTO os (numero_os, data_abertura) VALUES ('$os', '$data_abertura')";
if ($conn->query($sql) === TRUE) {
echo "<strong>".$os." - GRAVADO"."</strong>"."<p>";
} else {
echo "Error";
}
}
}
$conn->close();
?>
Change the line:
foreach($json_data['ordens_de_servico'] as $key => $value){
To:
foreach($json_data as $key => $value){
Since the new data doesn't have the outer element ordens_de_servico
Or you could edit the JSON file and add that element (don't forget to add the closing braces at the end as well.
Edit the first two lines of the file:
ordem_de_servico:
{
To:
{
"ordem_de_servico": [
And change the end of the file:
}
To:
]
}
Your JSON is incorrect. The main problem is json data itself which is not valid for json_encode() to generate PHP array.
First Possible solution:Remove ordem_de_servico: from our customer json and that will gonna work.
For json_decode(); method the json data must be valid and valid data is
{
"oser_numero_os":23940493,
"oser_dt_abertura":"28/03/2018",
"servico":{
"serv_cod_servico":60,
"serv_descr_servico":"CORTE POR DEBITO"
},
"cliente":{
"clie_ident_cliente":638617,
"nome":"MARIA APARECIDA FERREIRA DO NASCIMENTO"
},
"unidade_consumidora":{
"unid_ident_uc":2436434,
"logr_nome_logr_expandido":"R JOSE GUIMARAES"
},
"faturas":[
{
"total_fatura":"88.44",
"ftcd_mes_ano_fatmto":"2017-04-01"
},
{
"total_fatura":"45.16",
"ftcd_mes_ano_fatmto":"2017-03-01"
}
]
}
Second possible solution:What you can do is remove ordem_de_servico: string from your customer json data or make your json provider provide valid json data as follows with ordem_de_servico:.
{
"ordem_de_servico":{
"oser_numero_os":23940493,
"oser_dt_abertura":"28/03/2018",
"servico":{
"serv_cod_servico":60,
"serv_descr_servico":"CORTE POR DEBITO"
},
"cliente":{
"clie_ident_cliente":638617,
"nome":"MARIA APARECIDA FERREIRA DO NASCIMENTO"
},
"unidade_consumidora":{
"unid_ident_uc":2436434,
"logr_nome_logr_expandido":"R JOSE GUIMARAES"
},
"faturas":[
{
"total_fatura":"88.44",
"ftcd_mes_ano_fatmto":"2017-04-01"
},
{
"total_fatura":"45.16",
"ftcd_mes_ano_fatmto":"2017-03-01"
}
]
}
}
Look at the valid JSON format for json_decode() and there is not different types of json data only one type i.e. json.
This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 6 years ago.
I need PHP code to save data to a JSON file.
Needed result :
"calendar":[ {
"Pariharam":"pariharam",
"Palamozhi":"palamozhi",
"horoscopes":[
{
"HoroscopeID":"daily_horoscope_id",
"Rasiname":"Rasi",
"ShortDescription":"shot_desc",
"LongDescription":"long_desc"
},
}
]
My Code :
$sql=mysql_query("select * from daily_calendar_tbl");
$response = array();
$posts = array();
//$result=mysql_query($sql);
while($row=mysql_fetch_array($sql))
{
$caldate=$row['cal_date'];
$tamilyear=$row['tamil_year'];
$tamilmonth=$row['tamil_month'];
$tamildate=$row['tamil_date'];
$gtms=$row['gt_mrg_str'];
$gtme=$row['gt_mrg_end'];
$gtes=$row['gt_eve_str'];
$gtee=$row['gt_eve_end'];
$ggtms=$row['gow_mrg_str'];
$ggtme=$row['gow_mrg_end'];
$ggtes=$row['gow_eve_str'];
$ggtee=$row['gow_eve_end'];
$rst=$row['ragu_str'];
$ret=$row['ragu_end'];
$gst=$row['guli_str'];
$get=$row['guli_end'];
$yst=$row['yema_str'];
$yet=$row['yema_end'];
$sut=$row['sur_udha'];
$suras=$row['sur_astha'];
$yogam=$row['yogam'];
$chantrs=$row['chandrashtama'];
$soolam=$row['soolam'];
$phariharam=$row['pariharam'];
$palamozhi=$row['palamozhi'];
$selrasi=mysql_query("select * from daily_horoscope_tbl where horoscope_date='$caldate'");
while($rasidata=mysql_fetch_array($selrasi)){
$horoid=$rasidata["daily_horoscope_id"];
$rasiname=$rasidata["rasi"];
$shortdesc=$rasidata["shot_desc "];
$long_desc=$rasidata["long_desc"];
$horoscopedata[]=array('HoroscopeID'=> $horoid, 'Rasiname'=> $rasiname, 'ShortDescription'=>$shortdesc,'LongDescription'=> $long_desc);
}
$horoscopesres=$horoscopedata;
$posts[] = array('CalendarDate'=> $caldate, 'TamilYear'=> $tamilyear, 'TamilMonth'=>$tamilmonth,'TamilDate'=> $tamildate, 'GoodTimeMorningStart'=> $gtms,
'GoodTimeMorningEnd'=>$gtme,'GoodTimeEveningStart'=> $gtes, 'GoodTimeEveningEnd'=> $gtee, 'GowriGoodTimeMorningStart'=>$ggtms,'GowriGoodTimeMorningEnd'=> $ggtme, 'GowriGoodTimeEveningStart'=> $ggtes,
'GowriGoodTimeEveningEnd'=>$ggtee,'RahuStartTime'=> $rst, 'RahuEndTime'=> $ret, 'GulikaiStartTime'=>$gst,'GulikaiEndTime'=> $get, 'YamagandamStartTime'=> $yst,
'YamagandamEndTime'=>$yet,'SuryaUdhayamTime'=> $sut, 'SuryaAsthamanam'=> $suras, 'Yogam'=>$yogam,'Chandrashtama'=> $chantrs, 'Soolam'=> $soolam, 'Pariharam'=>$phariharam,'Palamozhi'=>$palamozhi,'horoscopes'=>$horoscopesres);
}
$response['calendardata'] = $posts;
$fp = fopen('articles.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
your json is not even a valid json try this
{
"calendar": {
"Pariharam": "pariharam",
"Palamozhi": "palamozhi",
"horoscopes": [{
"HoroscopeID": "daily_horoscope_id",
"Rasiname": "Rasi",
"ShortDescription": "shot_desc",
"LongDescription": "long_desc"
}]
}
}
secondly where do you want to pass array if you want horoscopes to be an array than it would look like
{
"calendar": {
"Pariharam": "pariharam",
"Palamozhi": "palamozhi",
"horoscopes": [{
"HoroscopeID": "daily_horoscope_id",
"Rasiname": "Rasi",
"ShortDescription": "shot_desc",
"LongDescription": "long_desc"
}, {
"HoroscopeID": "daily_horoscope_id",
"Rasiname": "Another",
"ShortDescription": "shot_desc",
"LongDescription": "long_desc"
}]
}
}
Something like this will work for you ..
you may have to do foreach loop for other dynamic elements.. You can have an idea from here. If you post your other codes i can update my answer.
$Pariharam = "pariharam";
$Palamozhi="palamozhi";
$horoscope= array('HoroscopeID'=>'daily_horoscope_id','Rasiname'=>'Rasi','ShortDescription'=>'shot_desc','LongDescription'=>'long_desc');
$calender=array();
$calender['calender']['Pariharam']=$Pariharam;
$calender['calender']['Palamozhi']=$Pariharam;
$calender['calender']['horoscope']=$horoscope;
print_r(json_encode($calender));exit;
Output
{
"calender":{
"Pariharam":"pariharam",
"Palamozhi":"pariharam",
"horoscope":{
"HoroscopeID":"daily_horoscope_id",
"Rasiname":"Rasi",
"ShortDescription":"shot_desc",
"LongDescription":"long_desc"
}
}
}
I have this php code that give data from database and then convert to a json text file, my database name is gengroup_testwebapp and my json file is jsonparsetutorial.txt :
<?php
// open a connection to mysql
$conn = mysqli_connect("localhost","gengroup_ali","GenGroup$2015","gengroup_testwebapp")
or die("Error is : ".mysqli_error($conn));
//fetching data to php
$sql = "select * from country_info";
$result = mysqli_query($conn , $sql) or die("Error is : ". mysqli_error($conn));
//create an array
$emparray[] = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
// convert php array to json String and \n
//write to json file
$fp = fopen('jsonparsetutorial.txt', 'worldpopulation');
fwrite($fp, json_encode($emparray));
fclose($fp); ?>
I wanna convert this code to json array file. how can I convert its data to a json file like this:
{ "worldpopulation":
[
{
"rank":1,"country":"China",
"population":"1,354,040,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/china.png"
},
{
"rank":2,"country":"India",
"population":"1,210,193,422",
"flag":"http://www.gengroup.ir/testwebapp/flag/india.png"
},
{
"rank":3,"country":"United States",
"population":"315,761,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/unitedstates.png"
},
{
"rank":4,"country":"Indonesia",
"population":"237,641,326",
"flag":"http://www.gengroup.ir/testwebapp/flag/indonesia.png"
},
{
"rank":5,"country":"Brazil",
"population":"193,946,886",
"flag":"http://www.gengroup.ir/testwebapp/flag/brazil.png"
},
{
"rank":6,"country":"Pakistan",
"population":"182,912,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/pakistan.png"
},
{
"rank":7,"country":"Nigeria",
"population":"170,901,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/nigeria.png"
},
{
"rank":8,"country":"Bangladesh",
"population":"152,518,015",
"flag":"http://www.gengroup.ir/testwebapp/flag/bangladesh.png"
},
{
"rank":9,"country":"Russia",
"population":"143,369,806",
"flag":"http://www.gengroup.ir/testwebapp/flag/russia.png"
},
{
"rank":10,"country":"Japan",
"population":"127,360,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/japan.png"
}
] }
Simply do this.
$arr['worldpopulation']= $emparray[];
$fp = fopen('jsonparsetutorial.txt', "w");
fwrite($fp, json_encode($arr));
fclose($fp); ?>
Don't forget to mention mode of open like w for write.