简体   繁体   中英

How to do recurring dates with php/MySQL

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, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM