I have a calendar
table in my MYSQL database with one field named datefield
(type DATE
).
Previously I inserted dates from 2008-01-01 to 2010-01-01 but now I want to add every day until the current date. Unfortunately, I'm completely forgotten how I did this.
I'm also wondering if there is any way to automate the process of keeping this table current.
I'm using PHP so I guess I could do a new INSERT
every day? Or is there some way to do this directly in MYSQL?
thanks, tim
Here's a quick hack:
drop table if exists dates;
create table dates(datefield date);
drop procedure if exists insertDates;
delimiter $$
create procedure insertDates(start_date date)
begin
set @days = 0;
set @end_date = str_to_date('1970-01-01', '%Y-%m-%d');
while (@end_date < curdate()) do
insert into dates
select
date_add(start_date, interval @days day)
from (select @days:=@days+1) r
;
set @end_date:=(select max(datefield) from dates);
end while
;
end $$
delimiter ;
call insertDates('2012-06-06');
select * from dates;
For the daily insert you can try a cron job or MySQL offers "EVENTS", something like:
CREATE EVENT yourDB_Schema.insertDateEachDay
ON SCHEDULE EVERY 1 DAY
DO
INSERT INTO yourTable (yourDateColumn) VALUES (CURDATE());
Read more about it here:
MySQL Create Event manual entry
An event is associated with a schema. If no schema is indicated as part of event_name, the default (current) schema is assumed.
_
Not specifying STARTS is the same as using STARTS CURRENT_TIMESTAMP—that is, the action specified for the event begins repeating immediately upon creation of the event.
I think the easiest way to do what you describe is set up a daily recurring task to run a php script, such as a cron job. There is also a web based provider that will call a script from your webserver on a cheap, recurring schedule. http://webcron.org