I have a query to get an array from a database.
$result = mysqli_query($con,"SELECT `Time_D` from `Schedule` where `Stop` = 1 ");
while ($row = mysqli_fetch_array($result) ) {
echo $row['Time_D'] . "<br>";
}
This array ($row) contains a lot of times, if I'm not mistaken.
I now want to add for example 10 minutes to all the elements in the array. How do I do that?
Well, figured it out myself after all.
$result = mysqli_query($con,"SELECT `Time_D` from `Schedule` where `Stop` = 1 ");
//get database result
while ($row = mysqli_fetch_array($result) ) {
$rows[] = $row['Time_D']; //store all the times in one array
}
print_r ($rows);
echo "<br>";
$time_difference=600;
$i=0;
while (($i) < (count($rows)) ) {
$rows[$i] = ( strtotime($rows[$i]) ) + ($time_difference); //with timestamps, because, well, php and times...
$rows[$i] = date('H:i:s', ($rows[$i]) ); // back from timestamp to time
$i = $i +1;
}
print_r($rows);
You need to update like this
$row['Time_D'] = time() + 600;
or just 10 seconds
$row['Time_D'] += 600;
Then push it back to the database
mysql_query('update table_name set Time_D = '{$row['Time_D']}' where id = '{$row['id']}'
OR something to that end.
You can do it from the mysql query itself by using DATE_ADD.
"SELECT DATE_ADD(`Time_D`,INTERVAL 10 MINUTE) AS 'Time_D' FROM `Schedule` WHERE `Stop` = 1 "
You can have a parameter like this in your php
script:
$minutes_to_add = 10;
$result = mysqli_query($con,"SELECT DATE_ADD(`Time_D`,INTERVAL ".$minutes_to_add." MINUTE) AS 'Time_D' FROM `Schedule` WHERE `Stop` = 1 ");
while ($row = mysqli_fetch_array($result) )
{
echo $row['Time_D'] . "<br>";
}
You can do it in SQL only:
"UPDATE `Schedule` SET `Time_D` VALUES = DATE_ADD(`Schedule`.`Time_D`,INTERVAL 10 MINUTE) where `Stop` = 1"
You might be mistaken. $row
does not contain a lot of times. As long as there are still records available, $row
is assigned the next row of the query result as an array. If you want to alter all the times, save them to a new array. In your while-loop (don't forget to declare $rows
):
$rows[] = $row['Time_D'];
$rows
now stores all the times. You can then (after the while-loop) iterate over $rows
and alter the data.
$rows = array_map(function($time) {
return $time + (60 * 10); // Given $time is a timestamp
}, $rows);
If you don't want to save the times (i.e. directly output them in the while-loop), save the overhead of array_map
and do it directly in the while-loop:
echo $row['Time_D'] + 60*10;
Depending on your exact situation you might want to use a key-value (i.e. id-to-time) storage for the times - otherwise you won't be able to refer them back to the "schedule" you are using.
If you only want to update the database records see Axel's answer.