PHP中如何通过循环将数组implode后插入MySQL数据库
问题:批量插入数组数据到MySQL失败
我尝试将$hour_prices数组插入MySQL数据库,但不确定如何通过循环实现该操作。我知道需要用implode处理数组,因为MySQL无法识别数组格式的数据,但数据库始终没有插入任何内容。不过使用关联数组时可以正常完成插入。
数组结构
Array ( [0] => Array ( [0] => 2023-01-22T23:00:00 [1] => DK2 [2] => 1103.27002 [3] => 0.1397 ) ) Array ( [0] => Array ( [0] => 2023-01-22T22:00:00 [1] => DK2 [2] => 1170.599976 [3] => 0.1397 ) ) Array ( [0] => Array ( [0] => 2023-01-22T21:00:00 [1] => DK2 [2] => 1237.920044 [3] => 0.1397 ) ) Array ( [0] => Array ( [0] => 2023-01-22T20:00:00 [1] => DK2 [2] => 1299.73999 [3] => 0.1397 ) ) Array ( [0] => Array ( [0] => 2023-01-22T19:00:00 [1] => DK2 [2] => 1481.709961 [3] => 0.1397 ) ) Array ( [0] => Array ( [0] => 2023-01-22T18:00:00 [1] => DK2 [2] => 1503.290039 [3] => 0.1397 ) ) Array ( [0] => Array ( [0] => 2023-01-22T17:00:00 [1] => DK2 [2] => 1428.300049 [3] => 0.4192 ) ) Array ( [0] => Array ( [0] => 2023-01-22T16:00:00 [1] => DK2 [2] => 1272.369995 [3] => 0.4192 ) ) Array ( [0] => Array ( [0] => 2023-01-22T15:00:00 [1] => DK2 [2] => 1143.52002 [3] => 0.4192 ) ) Array ( [0] => Array ( [0] => 2023-01-22T14:00:00 [1] => DK2 [2] => 1124.77002 [3] => 0.4192 ) ) Array ( [0] => Array ( [0] => 2023-01-22T13:00:00 [1] => DK2 [2] => 892.580017 [3] => 0.4192 ) ) Array ( [0] => Array ( [0] => 2023-01-22T12:00:00 [1] => DK2 [2] => 807.849976 [3] => 0.4192 ) ) Array ( [0] => Array ( [0] => 2023-01-22T11:00:00 [1] => DK2 [2] => 925.390015 [3] => 0.4192 ) ) Array ( [0] => Array ( [0] => 2023-01-22T10:00:00 [1] => DK2 [2] => 1023.960022 [3] => 0.4192 ) ) Array ( [0] => Array ( [0] => 2023-01-22T09:00:00 [1] => DK2 [2] => 900.099976 [3] => 0.4192 ) ) Array ( [0] => Array ( [0] => 2023-01-22T08:00:00 [1] => DK2 [2] => 639.869995 [3] => 0.4192 ) ) Array ( [0] => Array ( [0] => 2023-01-22T07:00:00 [1] => DK2 [2] => 482.970001 [3] => 0.4192 ) ) Array ( [0] => Array ( [0] => 2023-01-22T06:00:00 [1] => DK2 [2] => 456.929993 [3] => 1.2576 ) ) Array ( [0] => Array ( [0] => 2023-01-22T05:00:00 [1] => DK2 [2] => 465.630005 [3] => 1.2576 ) ) Array ( [0] => Array ( [0] => 2023-01-22T04:00:00 [1] => DK2 [2] => 520.840027 [3] => 1.2576 ) ) Array ( [0] => Array ( [0] => 2023-01-22T03:00:00 [1] => DK2 [2] => 531.549988 [3] => 1.2576 ) ) Array ( [0] => Array ( [0] => 2023-01-22T02:00:00 [1] => DK2 [2] => 543.530029 [3] => 0.4192 ) ) Array ( [0] => Array ( [0] => 2023-01-22T01:00:00 [1] => DK2 [2] => 588.97998 [3] => 0.4192 ) ) Array ( [0] => Array ( [0] => 2023-01-22T00:00:00 [1] => DK2 [2] => 590.690002 [3] => 0.4192 ) )
当前使用的PHP代码
<?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 ); echo "</br>"; print_r(array($hour_prices)); include "config.php"; } $sql = "INSERT INTO elpriser (HourDK, PriceArea, SpotPriceDKK, GridPrice) values "; $sql .= implode(',', $hour_prices); mysqli_query($con, $sql); echo "</br>"; echo "</br>"; print_r(array($hour_prices)); $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>"; } ?>
问题分析
- 循环覆盖变量:循环内每次给
$hour_prices赋值,最终只会保留最后一条数据,前面23条全部被覆盖。 - SQL语句格式错误:直接
implode(',', $hour_prices)生成的格式不符合MySQL要求,每条记录需要用括号包裹,字符串类型值必须加单引号,比如('2023-01-22T23:00:00','DK2',1103.27002,0.1397)。 - 重复引入配置文件:
include "config.php"放在循环内会重复执行24次,可能引发变量重复定义等问题。 - 无错误反馈机制:未检查
mysqli_query执行结果,无法定位SQL语句是否出错。 - SQL注入风险:直接将API返回数据拼接到SQL语句中,存在安全隐患。
修正后的代码
<?php // 仅一次引入数据库配置 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); // 收集所有待插入的格式化记录 $insertValues = []; for ($hour = 0; $hour < 24; $hour++) { // 转义字符串防止SQL注入,转换数值类型确保格式正确 $hourDK = mysqli_real_escape_string($con, $dataset_1['records'][$hour]['HourDK']); $priceArea = mysqli_real_escape_string($con, $dataset_1['records'][$hour]['PriceArea']); $spotPrice = (float)$dataset_1['records'][$hour]['SpotPriceDKK']; $gridPrice = (float)$dataset_2['records'][0]['Price' . ($hour + 1)]; // 拼接成MySQL要求的单条记录格式 $insertValues[] = "('$hourDK', '$priceArea', $spotPrice, $gridPrice)"; echo "</br>"; print_r([[$hourDK, $priceArea, $spotPrice, $gridPrice]]); } // 执行批量插入 if (!empty($insertValues)) { $sql = "INSERT INTO elpriser (HourDK, PriceArea, SpotPriceDKK, GridPrice) VALUES " . implode(', ', $insertValues); $result = mysqli_query($con, $sql); if ($result) { echo "</br></br>成功插入 " . mysqli_affected_rows($con) . " 条记录</br>"; } else { echo "</br></br>插入失败,错误信息:" . mysqli_error($con) . "</br>"; } } // 查询并展示数据 $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>"; } // 关闭数据库连接 mysqli_close($con); ?>
关键改进点
- 批量收集记录:用数组存储所有格式化后的记录,避免循环覆盖变量。
- 规范SQL格式:每条记录用括号包裹,字符串值加单引号,数值类型直接使用。
- 安全处理数据:用
mysqli_real_escape_string转义字符串,防范SQL注入。 - 增加错误反馈:检查插入结果并输出错误信息,方便调试。
- 优化资源使用:配置文件仅引入一次,操作完成后关闭数据库连接。
内容的提问来源于stack exchange,提问作者nhtj
相关产品推荐
相关产品推荐

