doushui3061 2015-11-30 15:11
浏览 141

将datetime对象递增5分钟并添加到数据库

Im trying to make a php script that takes a datetime and then uses a for loop to increment the date by 5 minutes and then add it to a mysql database. the code I have is this:

$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);

and when I echo insert it looks correct and I get the date time in the correct format but nothing is added to the database and I can't figure out why. Any ideas?

  • 写回答

1条回答 默认 最新

  • douchibu7040 2015-12-01 10:10
    关注

    I took Jon Stirlings advice and replaced my code with a prepared statement. the final code looks like this instead:

    $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);
        }
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么