I'm getting data from an API in JSON format. It's getting the resting heart rate of the user and inserting it into my database. It gets today's date as well as a couple days in the past and updates the database accordingly. The code below does work (although it's inserting a blank row for some reason). My question is, is there a better/more efficient way of writing this code?
Here is the array:
[activities-heart] => Array (
[0] => Array (
[dateTime] => 2018-03-22
[value] => Array (
[customHeartRateZones] => Array ( )
[heartRateZones] => Array (
[0] => Array (
[caloriesOut] => 1135.7736
[max] => 85
[min] => 30
[minutes] => 814
[name] => Out of Range
)
[1] => Array (
[caloriesOut] => 1260.7179
[max] => 119
[min] => 85
[minutes] => 289
[name] => Fat Burn
)
[2] => Array (
[caloriesOut] => 690.64515
[max] => 145
[min] => 119
[minutes] => 90
[name] => Cardio
)
[3] => Array (
[caloriesOut] => 0
[max] => 220
[min] => 145
[minutes] => 0
[name] => Peak
)
)
[restingHeartRate] => 65
)
)
[1] => Array (
[dateTime] => 2018-03-23
[value] => Array (
[customHeartRateZones] => Array ( )
[heartRateZones] => Array (
[0] => Array (
[caloriesOut] => 1512.00346
[max] => 85
[min] => 30
[minutes] => 1113
[name] => Out of Range
)
[1] => Array (
[caloriesOut] => 1315.59604
[max] => 119
[min] => 85
[minutes] => 280
[name] => Fat Burn
)
[2] => Array (
[caloriesOut] => 98.14618
[max] => 145
[min] => 119
[minutes] => 13
[name] => Cardio
)
[3] => Array (
[caloriesOut] => 0
[max] => 220
[min] => 145
[minutes] => 0
[name] => Peak
)
)
[restingHeartRate] => 64
)
)
)
And here is the relevant code to process it:
$obj = new RecursiveIteratorIterator( new RecursiveArrayIterator( json_decode( $return, TRUE ) ), RecursiveIteratorIterator::SELF_FIRST );
foreach ( $obj as $key => $val ) {
$$key = $val;
$stmt = $connection->prepare( "INSERT INTO heartrate SET `encodedid` = ?, activitydate = ?, rhr = ? ON DUPLICATE KEY UPDATE rhr= ?" );
$stmt->bind_param( 'ssii', $studentencodedid, $dateTime, $restingHeartRate, $restingHeartRate );
$stmt->execute();
if ( $stmt->affected_rows < 1 ) {
header( "Location: " . $url . "/index.php?errormessage=Failed to updated the resting heart rate value." );
}
$stmt->close();
}
if
statement condition is true? Please include more context in your code. This isn’t exactly hypothetical code but please see Why is hypothetical example code off-topic for CR? \$\endgroup\$