cankemik
cankemik

Reputation: 524

how to insert time as string by time intervals into mysql database

In my project i need time intervals by 15 minutes in my database such as "06.00", "06:15".. There is a time_id and time_interval column in my time table. I want to keep the time intervals as strings in my database and give everyone of them an id.

I wrote the query below:

mysql_query("INSERT INTO time(time_interval) VALUES('06:00'),('06:15'),('06:30') ...");

and i though there should be a easy way. I googled it a lot bu nothing seem to work. So how do i do this in a short way ?

Upvotes: 1

Views: 683

Answers (1)

Glavić
Glavić

Reputation: 43552

You can use DateTime to get all times between 2 times:

$dt1 = new DateTime('06:00 UTC');
$dt2 = new DateTime('16:00 UTC');

$values = array();
while ($dt1 <= $dt2) {
    $values[] = $dt1->format("('H:i')");
    $dt1->modify('+15 minute');
}

And then you can use that array to build your query:

$sql = "INSERT INTO time(time_interval) VALUES " . implode(', ', $values);
print_r($sql);

Demo.

Upvotes: 3

Related Questions