开发者

How to do recurring dates with php/MySQL

开发者 https://www.devze.com 2023-03-24 14:09 出处:网络
I have a table: table Event - name - description - date (in format 2011-08-06 11:00:00) - id I need to create recurring events.

I have a table:

table Event
- name
- description
- date (in format 2011-08-06 11:00:00)
- id

I need to create recurring events.

How can I best duplicate a row with mostly the same data (name, description) but change the date?

Say, if I have an event that occurs August 6th, I would like to create three more events on - August 13, 20开发者_如何学JAVA, 27 (every Saturday)

Also, is this something better accomplished with a mySQL query? I am guessing so because of the format the date is in...but any advice would be appreciated.


MySQL lacks a generator functionality (which would allow to create arbitrary length recordsets from scratch), so if the number of records is fixed, you could do something like that:

INSERT
INTO    event (name, description, date)
SELECT  name, description, date + INTERVAL n WEEK
FROM    (
        SELECT  1 AS n
        UNION ALL
        SELECT  2 AS n
        UNION ALL
        SELECT  3 AS n
        ) q
JOIN    event
ON      id = $myid

As you can see, the query layout depends on the number of events to create, with pure SQL there is no way to parameterize it.

You, however, can create a stored procedure and just call INSERT in a loop:

CREATE PROCEDURE prc_fill_event (p_id INT, p_cnt INT)
BEGIN
        DECLARE _cnt INT;
        SET _cnt = 1;
        WHILE _cnt <= p_cnt DO
                INSERT
                INTO    event (name, description, date)
                SELECT  name, description, date + INTERVAL _cnt WEEK
                FROM    event
                WHERE   id = p_id;
                SET _cnt = _cnt + 1;
        END WHILE;
END


Depends. If it's a recurring date that goes on into infinity, that's gonna be a lot of rows to create. Or you'd have to choose some limit on that, and that starts to complicate the problem.

Maybe it'd be better to have additional columns that describe recurring events, and then render them accordingly in your view layers.

0

精彩评论

暂无评论...
验证码 换一张
取 消