I have created an API
which returns me an array of data in json
Array ( [0] => stdClass Object ( [MSN] => 002999001207 [PingDateTime] => 2018-05-04T16:33:27 [PingValue] => 22 ) [1] => stdClass Object ( [MSN] => 002999001195 [PingDateTime] => 2018-05-04T16:34:11 [PingValue] => 21 ) [2] => stdClass Object ( [MSN] => 002999001180 [PingDateTime] => 2018-05-04T14:42:40 [PingValue] => 20 ) [3] => stdClass Object ( [MSN] => 002999001157 [PingDateTime] => 2018-05-04T14:42:52 [PingValue] => 30 ) [4] => stdClass Object ( [MSN] => 002999001142 [PingDateTime] => 2018-05-04T16:37:19 [PingValue] => 13 ) [5] => stdClass Object ( [MSN] => 002999001138 [PingDateTime] => 2018-05-04T16:32:22 [PingValue] => 20 ) [6] => stdClass Object ( [MSN] => 002999001114 [PingDateTime] => 2018-05-04T16:32:52 [PingValue] => 22 )
Now, I am trying to save it in my DB
$curl = curl_init($api_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 1000);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Key'));
$m->start_date_time = date('Y-m-d h:i:s');
$curl_response = curl_exec($curl);
$json = json_decode($curl_response);
$record = $json->data;
foreach ($record as $item){
if($this->isSaved($item->MSN))
{
return false;
}
else if($this->ogpCreated($item->MSN))
{
$m->end_date_time = date('Y-m-d h:i:s');
$m->meter_msn = $item->MSN;
$m->meter_id = Meters::msnmapToid($m->meter_msn);
$m->sub_div_code = Ogpdetail::msnTosubdiv($item->MSN);
$m->sub_div_name = Ogpdetail::subDivToName($m->sub_div_code);
$m->meter_ping_date_time = str_replace('T', ' ', $item->PingDateTime);
$m->save();
}
}
return $this->redirect(['index']);
In above code, there are two if conditions
isSaved($item->MSN)
$meter = MeterPing::find()->where(['meter_msn' => $msn])->one();
if($meter)
return true;
return false;
From the above function, I am trying to check whether the incoming MSN
is already saved or not. If it's already present in the table it will not save that particular MSN
but yes save all the other MSN
that are not saved previously.
ogpCreated($item->MSN)
$meter = Ogpdetail::find()->where(['meter_serial' => $msn])->one();
if($meter)
return true;
return false;
From the above function, I am trying to check that the incoming MSN
is OGP
created or not. Again it should not save any MSN
which is not OGP
created.
Now, when I try to run this Create
function it only saves one record at a time.
I think there is some issue in if..... elseif
that only allows saving one entry. But I am not sure of that.
Update 1
I have tried to remove the checks and then save the incoming data but still, it only saves one record
How can I save the entire received JSON
data into my DB
with all checks working?