Hello everyone,
I need some help here, I got stuck. Im beginner in programming so if someone can explain to me what I am doing wrong since i cant insert my imploded array to the MySQL database. As i understand, to insert an array of data to MySQL I have to convert the datatype for the array so MySQL can understand the dataformat. There are more ways of doing that. I chose implode and my datatype output looks comma seperated. I then query to the database, but nothing is inserted. Below is my code. Thanks :-)
<?php
// DB connection
include "config.php";
// Brooker pricelist
$url1 = 'https://api.energidataservice.dk/dataset/Elspotprices?start=2023-01-22T00%3A00&end=2023-01-23T00%3A00&columns=HourDK%2C%20PriceArea%2C%20SpotPriceDKK&filter=%7B%22PriceArea%22%3A%20%22DK2%22%7D';
// Grid pricelist
$url2 = 'https://api.energidataservice.dk/dataset/DatahubPricelist?start=2023-01-22T00%3A00&end=2023-01-23T00%3A00&filter=%7B%22ChargeOwner%22%3A%20%22TREFOR%20El-net%20A%2FS%22%2C%20%22Note%22%3A%20%22Nettarif%20C%20time%22%7D&limit=1&timezone=DK';
$json1 = file_get_contents($url1);
$json2 = file_get_contents($url2);
$dataset_1 = json_decode($json1, true);
$dataset_2 = json_decode($json2, true);
for ($hour = 0; $hour < 24; $hour++) {
$hour_prices = array(
$dataset_1['records'][$hour]['HourDK'] // HourDK
, $dataset_1['records'][$hour]['PriceArea'] // PriceArea
, $dataset_1['records'][$hour]['SpotPriceDKK'] // SpotPriceDKK
, $dataset_2['records'][0]['Price' . ($hour + 1)] // GridPrice
);
// Insert, does not work
$array_data = implode(", ", $hour_prices);
$sql = "INSERT INTO elpriser (HourDK, PriceArea, SpotPriceDKK, GridPrice) VALUES('" . $array_data . "');";
mysqli_query($con, $sql);
//echo "</br>";
//print_r (array($array_data));
//echo var_dump($array_data);
}
// Select, works
$sql = mysqli_query($con,"SELECT * FROM elpriser");
while($row = mysqli_fetch_assoc($sql)){
$HourDK = $row['HourDK'];
$PriceArea = $row['PriceArea'];
$SpotPriceDKK = $row['SpotPriceDKK'];
$GridPrice = $row['GridPrice'];
echo "Timepris : ".$HourDK.", Region : ".$PriceArea.", Pris elbørs : ".$SpotPriceDKK.", Pris elnet : ".$GridPrice."<br>";
}
?>