Question

Given that I have table (events) that amoung others contains the columns date, reoccur and frequency

where reoccur may be an enum:'d', 'w' or y for days, weeks or years

+---------------------+-----------+-------------+
| eventdate           | reoccur   | frequency   |
+---------------------+-----------+-------------+
| 2014-03-31 00:00:00 | w         |           4 |
| 2014-07-01 00:00:00 | d         |           7 |
+---------------------+-----------+-------------+

How would I go about selecting a row for each reoccurring event within a chosen year?

I presume I'd need a mysql while loop to achieve this? I've been studying possibilities for some time and I'm still stuck with where to begin

Was it helpful?

Solution

I guess this can be done with MySQL, but I think I'd favour an application level approach, something like the following. Note, I'm no expert when it comes to PHP, and, for simplicity and clarity (and possibly at the cost of some flexibility), I've amended your design slightly...

DDLs:

CREATE TABLE events
(event_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,event_date DATE NOT NULL
,recurrence_pattern  ENUM('day','week','month','year') NULL
,no_of_occurrences   INT NULL
);

INSERT INTO events VALUES
(1,'2014-03-31 00:00:00','week',4),
(2,'2014-07-01 00:00:00','day',7);

PHP:

<?php
include('path/to/connection/stateme.nts');

$query = "
  SELECT event_id
       , event_date
       , recurrence_pattern
       , no_of_occurrences
    FROM events
   ORDER
      BY event_date;
";

$result = mysqli_query($db,$query);

while($row = mysqli_fetch_assoc($result)){
for($i=0;$i<$row['no_of_occurrences'];$i++){
echo date('Y-m-d',strtotime("{$row['event_date']} + $i {$row['recurrence_pattern']}")), "\n";
}
}
?>

Outputs:

2014-03-31
2014-04-07
2014-04-14
2014-04-21

2014-07-01
2014-07-02
2014-07-03
2014-07-04
2014-07-05
2014-07-06
2014-07-07
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top