我试图制作一个需要日期时间的PHP脚本,然后使用for循环将日期增加5分钟,然后将其添加到mysql数据库中。我的代码就是:
$minutes_to_add = 5;
$time = new DateTime('2014-12-11 00:00:00');
for($i = 0; $i < 10; $i++){
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
$insert = date_format($time, 'Y-m-d H:i:s');
mysqli_query($conn, "INSERT INTO sensordata (GreenhouseID, Light, Earthmoisture, Waterlevel, Airparticles, CO2, RH, Temp, Dateandtime) VALUES (1,RAND() * 298 + 2,RAND() * 298 + 2,RAND() * 298 + 2,RAND() * 298 + 2,RAND() * 298 + 2,RAND() * 298 + 2,RAND() * 298 + 2, $insert");
}
echo json_encode($insert);
当我回显插入它看起来是正确的,我得到正确格式的日期时间,但没有任何东西添加到数据库,我无法弄清楚原因。有什么想法吗?
答案 0 :(得分:0)
我接受了Jon Stirlings的建议,并用准备好的声明替换了我的代码。最终的代码看起来像这样:
$minutes_to_add = 5;
$datetime = new DateTime('2014-12-11 00:00:00');
for($i = 0; $i < 10; $i++){
$datetime->add(new DateInterval('PT' . $minutes_to_add . 'M'));
$date = date_format($datetime, 'Y-m-d H:i:s');
if($stmt = mysqli_prepare($conn, "INSERT INTO sensordata (GreenhouseID, Light, Earthmoisture, Waterlevel, Airparticles, CO2, RH, Temp, Dateandtime) VALUES (1,RAND() * 298 + 2,RAND() * 298 + 2,RAND() * 298 + 2,RAND() * 298 + 2,RAND() * 298 + 2,RAND() * 298 + 2,RAND() * 298 + 2, ?)")){
mysqli_stmt_bind_param($stmt, "s", $date);
mysqli_stmt_execute($stmt);
}
}