5 * Fetch data from an SQL database
15 public function __construct($config)
17 $this->dsn = $config['dsn'];
18 $this->user = $config['user'];
19 $this->password = $config['password'];
20 $this->table = $config['table'];
21 $this->fields = $config['fields'];
25 * @param string $strDate Date the events shall be found for, YYYY-MM-DD
27 public function getEvents($strDate, $nDaysPrevious, $nDaysNext)
29 $dbh = new \PDO($this->dsn, $this->user, $this->password);
30 $arDays = $this->getDates($strDate, $nDaysPrevious, $nDaysNext);
33 foreach ($this->fields['date'] as $field => $typeName) {
34 $sqlMonth = 'EXTRACT(MONTH FROM ' . $field . ')';
35 $sqlDay = 'EXTRACT(DAY FROM ' . $field . ')';
38 foreach ($arDays as $month => $days) {
40 . $sqlMonth . ' = ' . $dbh->quote($month, \PDO::PARAM_INT)
41 . ' AND ' . $sqlDay . ' >= '
42 . $dbh->quote(min($days), \PDO::PARAM_INT)
43 . ' AND ' . $sqlDay . ' <= '
44 . $dbh->quote(max($days), \PDO::PARAM_INT)
47 $sql = 'SELECT ' . $field . ' AS e_date'
48 . ', ' . $this->fields['name'] . ' AS e_name'
49 . ' FROM ' . $this->table
51 . implode(' OR ', $parts);
53 $res = $dbh->query($sql);
55 $errorInfo = $dbh->errorInfo();
57 'SQL error #' . $errorInfo[0]
58 . ': ' . $errorInfo[1]
59 . ': ' . $errorInfo[2],
63 while ($row = $res->fetchObject()) {
65 $row->e_name, $typeName,
66 str_replace('0000', '????', $row->e_date)
68 if ($event->isWithin($strDate, $nDaysPrevious, $nDaysNext)) {
77 * @return array Key is the month, value an array of days
79 protected function getDates($strDate, $nDaysPrevious, $nDaysNext)
81 $ts = strtotime($strDate) - 86400 * $nDaysPrevious;
82 $numDays = $nDaysPrevious + $nDaysNext;
86 $arDays[(int) date('n', $ts)][] = (int) date('j', $ts);
88 } while (--$numDays >= 0);