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?
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);
}
}