Simple Events Calendar With PHP MySQL (Free Code Download)

Welcome to a tutorial on how to build an AJAX-driven events calendar with PHP and MySQL. Looking to add some organizational features to your project? Too many calendars out there that are too complicated?

A simple PHP MySQL calendar only consists of a few key components:

  • A database table to store the events.
  • A PHP class library to manage the events.
  • Lastly, an HTML page to show the calendar of events.

But just how is this done exactly? Let us walk through a step-by-step example in this guide – Read on!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

PHP MYSQL EVENTS CALENDAR

All right, let us now get into the details of building a PHP MYSQL calendar.

 

 

PART 1) EVENTS DATABASE TABLE

1-database.sql
CREATE TABLE `events` (
  `evt_id` bigint(20) NOT NULL,
  `evt_start` datetime NOT NULL,
  `evt_end` datetime NOT NULL,
  `evt_text` text NOT NULL,
  `evt_color` varchar(7) NOT NULL,
  `evt_bg` varchar(7) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
 
ALTER TABLE `events`
  ADD PRIMARY KEY (`evt_id`),
  ADD KEY `evt_start` (`evt_start`),
  ADD KEY `evt_end` (`evt_end`);
 
ALTER TABLE `events`
  MODIFY `evt_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

Let us start by dealing with the foundation of the system – A database table to save all the event entries.

Field Description
evt_id Primary key, auto-increment.
evt_start Event start date.
evt_end Event end date.
evt_text Details of the event.
evt_color Color of the text.
evt_bg Background color.

 

 

PART 2) PHP CALENDAR LIBRARY

2-cal-lib.php
<?php
class Calendar {
  // (A) CONSTRUCTOR - CONNECT TO DATABASE
  private $pdo = null;
  private $stmt = null;
  public $error = "";
  function __construct () {
    $this->pdo = new PDO(
      "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET, 
      DB_USER, DB_PASSWORD, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
  }

  // (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
  function __destruct () {
    if ($this->stmt!==null) { $this->stmt = null; }
    if ($this->pdo!==null) { $this->pdo = null; }
  }
 
  // (C) HELPER - RUN SQL QUERY
  function query ($sql, $data=null) : void {
    $this->stmt = $this->pdo->prepare($sql);
    $this->stmt->execute($data);
  }
 
  // (D) SAVE EVENT
  function save ($start, $end, $txt, $color, $bg, $id=null) {
    // (D1) START & END DATE CHECK
    if (strtotime($end) < strtotime($start)) {
      $this->error = "End date cannot be earlier than start date";
      return false;
    }
 
    // (D2) RUN SQL
    if ($id==null) {
      $sql = "INSERT INTO `events` (`evt_start`, `evt_end`, `evt_text`, `evt_color`, `evt_bg`) VALUES (?,?,?,?,?)";
      $data = [$start, $end, strip_tags($txt), $color, $bg];
    } else {
      $sql = "UPDATE `events` SET `evt_start`=?, `evt_end`=?, `evt_text`=?, `evt_color`=?, `evt_bg`=? WHERE `evt_id`=?";
      $data = [$start, $end, strip_tags($txt), $color, $bg, $id];
    }
    $this->query($sql, $data);
    return true;
  }
 
  // (E) DELETE EVENT
  function del ($id) {
    $this->query("DELETE FROM `events` WHERE `evt_id`=?", [$id]);
    return true;
  }
 
  // (F) GET EVENTS FOR SELECTED PERIOD
  function get ($month, $year) {
    // (F1) DATE RANGE CALCULATIONS
    $month = $month<10 ? "0$month" : $month ;
    $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    $dateYM = "{$year}-{$month}-";
    $start = $dateYM . "01 00:00:00";
    $end = $dateYM . $daysInMonth . " 23:59:59";
 
    // (F2) GET EVENTS
    // s & e : start & end date
    // c & b : text & background color
    // t : event text
    $this->query("SELECT * FROM `events` WHERE (
      (`evt_start` BETWEEN ? AND ?)
      OR (`evt_end` BETWEEN ? AND ?)
      OR (`evt_start` <= ? AND `evt_end` >= ?)
    )", [$start, $end, $start, $end, $start, $end]);
    $events = [];
    while ($r = $this->stmt->fetch()) {
      $events[$r["evt_id"]] = [
        "s" => $r["evt_start"], "e" => $r["evt_end"],
        "c" => $r["evt_color"], "b" => $r["evt_bg"],
        "t" => $r["evt_text"]
      ];
    }
 
    // (F3) RESULTS
    return count($events)==0 ? false : $events ;
  }
}

// (G) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");

// (H) NEW CALENDAR OBJECT
$_CAL = new Calendar();

This library looks massive at first, but keep calm and look carefully.

  • (A, B, H) When $_CAL = new Calendar() is created, the constructor connects to the database. The destructor closes the connection.
  • (C) query() is a helper function to run an SQL query.
  • (D To F) The “actual library functions”.
    • (D) save() Saves an event (insert or update).
    • (E) del() Deletes an event.
    • (F) get() Gets the events for a selected month/year.
  • (G) Remember to change the database settings to your own.

 

 

PART 3) CALENDAR AJAX HANDLER

3-cal-ajax.php
<?php
if (isset($_POST["req"])) {
  // (A) LOAD LIBRARY
  require "2-cal-lib.php";
  switch ($_POST["req"]) {
    // (B) GET DATES & EVENTS FOR SELECTED PERIOD
    case "get":
      echo json_encode($_CAL->get($_POST["month"], $_POST["year"]));
      break;

    // (C) SAVE EVENT
    case "save":
      echo $_CAL->save(
        $_POST["start"], $_POST["end"], $_POST["txt"], $_POST["color"], $_POST["bg"],
        isset($_POST["id"]) ? $_POST["id"] : null
      ) ? "OK" : $_CAL->error ;
      break;

    // (D) DELETE EVENT
    case "del":
      echo $_CAL->del($_POST["id"])  ? "OK" : $_CAL->error ;
      break;
  }
}

This AJAX handler pretty much “maps $_POST requests to library functions”. For example, we send $_POST["req"] = "del" and $_POST["id"] = 123 to delete an event.

 

PART 4) CALENDAR PAGE

4A) HTML PAGE

4a-cal-page.php
<?php
// (A) DAYS MONTHS YEAR
$months = [
  1 => "January", 2 => "Febuary", 3 => "March", 4 => "April",
  5 => "May", 6 => "June", 7 => "July", 8 => "August",
  9 => "September", 10 => "October", 11 => "November", 12 => "December"
];
$monthNow = date("m");
$yearNow = date("Y"); ?>
 
<!-- (B) PERIOD SELECTOR -->
<div id="calHead">
  <div id="calPeriod">
    <input id="calToday" type="button" value="&#9733;">
    <input id="calBack" type="button" class="mi" value="&lt;">
    <select id="calMonth"><?php foreach ($months as $m=>$mth) {
      printf("<option value='%u'%s>%s</option>",
        $m, $m==$monthNow?" selected":"", $mth
      );
    } ?></select>
    <input id="calYear" type="number" value="<?=$yearNow?>">
    <input id="calNext" type="button" class="mi" value="&gt;">
  </div>
  <input id="calAdd" type="button" value="+">
</div>
 
<!-- (C) CALENDAR WRAPPER -->
<div id="calWrap">
  <div id="calDays"></div>
  <div id="calBody"></div>
</div>
 
<!-- (D) EVENT FORM -->
<dialog id="calForm"><form method="dialog">
  <div id="evtCX">X</div>
  <h2 class="evt100">CALENDAR EVENT</h2>
  <div class="evt50">
    <label>Start</label>
    <input id="evtStart" type="datetime-local" required>
  </div>
  <div class="evt50">
    <label>End</label>
    <input id="evtEnd" type="datetime-local" required>
  </div>
  <div class="evt50">
    <label>Text Color</label>
    <input id="evtColor" type="color" value="#000000" required>
  </div>
  <div class="evt50">
    <label>Background Color</label>
    <input id="evtBG" type="color" value="#ffdbdb" required>
  </div>
  <div class="evt100">
    <label>Event</label>
    <input id="evtTxt" type="text" autocomplete="off" required>
  </div>
  <div class="evt100">
    <input type="hidden" id="evtID">
    <input type="button" id="evtDel" value="Delete">
    <input type="submit" id="evtSave" value="Save">
  </div>
</form></dialog>

  1. Month and year “data stuff”.
  2. <div id="calPeriod"> The month and year selector.
  3. <div id="calWrap"> The calendar itself – The HTML will be generated with Javascript.
  4. <form id="calForm"> A hidden popup form to add/update an event.

P.S. I am using native <input type="datetime-local"> and <input type="color">. Feel free to implement and use your own library if you want – React, Angular, Vue, jQuery, etc…

 

 

4B) JAVASCRIPT INITIALIZE

4b-calendar.js
var cal = {
  // (A) PROPERTIES
  mon : false, // monday first
  events : null, // events data for current month/year
  sMth : 0, sYear : 0, // selected month & year
  hMth : null, hYear : null, // html month & year
  hCD : null, hCB : null, // html calendar days & body
  // html form & fields
  hFormWrap : null, hForm : null, hfID : null, 
  hfStart : null, hfEnd : null, hfTxt : null,
  hfColor : null, hfBG : null, hfDel : null,

  // (B) SUPPORT FUNCTION - AJAX FETCH
  ajax : (data, onload) => {
    // (B1) FORM DATA
    let form = new FormData();
    for (let [k,v] of Object.entries(data)) { form.append(k,v); }

    // (B2) FETCH
    fetch("3-cal-ajax.php", { method:"POST", body:form })
    .then(res => res.text())
    .then(txt => onload(txt))
    .catch(err => console.error(err));
  },
 
  // (C) INIT CALENDAR
  init : () => {
    // (C1) GET HTML ELEMENTS
    cal.hMth = document.getElementById("calMonth");
    cal.hYear = document.getElementById("calYear");
    cal.hCD = document.getElementById("calDays");
    cal.hCB = document.getElementById("calBody");
    cal.hFormWrap = document.getElementById("calForm");
    cal.hForm = cal.hFormWrap.querySelector("form");
    cal.hfID = document.getElementById("evtID");
    cal.hfStart = document.getElementById("evtStart");
    cal.hfEnd = document.getElementById("evtEnd");
    cal.hfTxt = document.getElementById("evtTxt");
    cal.hfColor = document.getElementById("evtColor");
    cal.hfBG = document.getElementById("evtBG");
    cal.hfDel = document.getElementById("evtDel");
 
    // (C2) ATTACH CONTROLS
    cal.hMth.onchange = cal.load;
    cal.hYear.onchange = cal.load;
    document.getElementById("calToday").onclick = () => cal.today();
    document.getElementById("calBack").onclick = () => cal.pshift();
    document.getElementById("calNext").onclick = () => cal.pshift(1);
    document.getElementById("calAdd").onclick = () => cal.show();
    cal.hForm.onsubmit = () => cal.save();
    document.getElementById("evtCX").onclick = () => {
      if (document.startViewTransition) { document.startViewTransition(() => cal.hFormWrap.close()); }
      else { cal.hFormWrap.close(); }
    }
    cal.hfDel.onclick = cal.del;
 
    // (C3) DRAW DAY NAMES
    let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    if (cal.mon) { days.push("Sun"); } else { days.unshift("Sun"); }
    for (let d of days) {
      let cell = document.createElement("div");
      cell.className = "calCell";
      cell.innerHTML = d;
      cal.hCD.appendChild(cell);
    }
 
    // (C4) LOAD & DRAW CALENDAR
    cal.load();
  },
  // ...
};
window.onload = cal.init;

Once again, we have some “long stinky Javascript”. But look carefully, the first few sections should be self-explanatory.

  • var cal is an object that contains all the “calendar mechanics”.
  • (A & C) On window load, cal.init() will run. All it does is get the HTML elements, “enable” them, and draw the “day names”.
  • (B) cal.ajax() is a helper function to do a fetch() call to 3-cal-ajax.php.

 

4C) JAVASCRIPT PERIOD SHIFT

4b-calendar.js
// (D) SHIFT CURRENT PERIOD BY 1 MONTH
pshift : forward => {
  cal.sMth = parseInt(cal.hMth.value);
  cal.sYear = parseInt(cal.hYear.value);
  if (forward) { cal.sMth++; } else { cal.sMth--; }
  if (cal.sMth > 12) { cal.sMth = 1; cal.sYear++; }
  if (cal.sMth < 1) { cal.sMth = 12; cal.sYear--; }
  cal.hMth.value = cal.sMth;
  cal.hYear.value = cal.sYear;
  cal.load();
},
 
// (E) JUMP TO TODAY
today : () => {
  let now = new Date(), ny = now.getFullYear(), nm = now.getMonth()+1;
  if (ny!=cal.sYear || (ny==cal.sYear && nm!=cal.sMth)) {
    cal.hMth.value = nm;
    cal.hYear.value = ny;
    cal.load();
  }
},
  • cal.pshift() Drive the last/next month buttons. It pretty much adds/minus one from the current month.
  • cal.today() “Jumps” back to the current month/year.

 

 

4D) JAVASCRIPT LOAD & DRAW CALENDAR

4b-calendar.js
// (F) LOAD EVENTS
load : () => {
  cal.sMth = parseInt(cal.hMth.value);
  cal.sYear = parseInt(cal.hYear.value);
  cal.ajax({
    req : "get", month : cal.sMth, year : cal.sYear
  }, events => {
    cal.events = JSON.parse(events);
    cal.draw();
  });
},
 
// (G) DRAW CALENDAR
draw : () => {
  // (G1) CALCULATE DAY MONTH YEAR
  // note - jan is 0 & dec is 11 in js
  // note - sun is 0 & sat is 6 in js
  let daysInMth = new Date(cal.sYear, cal.sMth, 0).getDate(), // number of days in selected month
      startDay = new Date(cal.sYear, cal.sMth-1, 1).getDay(), // first day of the month
      endDay = new Date(cal.sYear, cal.sMth-1, daysInMth).getDay(), // last day of the month
      now = new Date(), // current date
      nowMth = now.getMonth()+1, // current month
      nowYear = parseInt(now.getFullYear()), // current year
      nowDay = cal.sMth==nowMth && cal.sYear==nowYear ? now.getDate() : null ;
 
  // (G2) DRAW CALENDAR ROWS & CELLS
  // (G2-1) INIT
  let rowA, rowB, rowC, rowMap = {}, rowNum = 1, cell, cellNum = 1,
 
  // (G2-2) HELPER - DRAW A NEW ROW
  rower = () => {
    rowA = document.createElement("div");
    rowB = document.createElement("div");
    rowC = document.createElement("div");
    rowA.className = "calRow";
    rowA.id = "calRow" + rowNum;
    rowB.className = "calRowHead";
    rowC.className = "calRowBack";
    cal.hCB.appendChild(rowA);
    rowA.appendChild(rowB);
    rowA.appendChild(rowC);
  },
 
  // (G2-3) HELPER - DRAW A NEW CELL
  celler = day => {
    cell = document.createElement("div");
    cell.className = "calCell";
    if (day) {
      cell.innerHTML = day;
      cell.classList.add("calCellDay");
      cell.onclick = () => {
        cal.show();
        let d = +day, m = +cal.hMth.value,
            s = `${cal.hYear.value}-${String(m<10 ? "0"+m : m)}-${String(d<10 ? "0"+d : d)}T00:00:00`;
        cal.hfStart.value = s;
        cal.hfEnd.value = s;
      };
    }
    rowB.appendChild(cell);
    cell = document.createElement("div");
    cell.className = "calCell";
    if (day===undefined) { cell.classList.add("calBlank"); }
    if (day!==undefined && day==nowDay) { cell.classList.add("calToday"); }
    rowC.appendChild(cell);
  };
 
  // (G2-4) RESET CALENDAR
  cal.hCB.innerHTML = ""; rower();
 
  // (G2-5) BLANK CELLS BEFORE START OF MONTH
  if (cal.mon && startDay != 1) {
    let blanks = startDay==0 ? 7 : startDay ;
    for (let i=1; i<blanks; i++) { celler(); cellNum++; }
  }
  if (!cal.mon && startDay != 0) {
    for (let i=0; i<startDay; i++) { celler(); cellNum++; }
  }
 
  // (G2-6) DAYS OF THE MONTH
  for (let i=1; i<=daysInMth; i++) {
    rowMap[i] = { r : rowNum, c : cellNum };
    celler(i);
    if (i!=daysInMth && cellNum%7==0) { rowNum++; rower(); }
    cellNum++;
  }
 
  // (G2-7) BLANK CELLS AFTER END OF MONTH
  if (cal.mon && endDay != 0) {
    let blanks = endDay==6 ? 1 : 7-endDay;
    for (let i=0; i<blanks; i++) { celler(); cellNum++; }
  }
  if (!cal.mon && endDay != 6) {
    let blanks = endDay==0 ? 6 : 6-endDay;
    for (let i=0; i<blanks; i++) { celler(); cellNum++; }
  }
 
  // (G3) DRAW EVENTS
  if (cal.events !== false) { for (let [id,evt] of Object.entries(cal.events)) {
    // (G3-1) EVENT START & END DAY
    let sd = new Date(evt.s), ed = new Date(evt.e);
    if (sd.getFullYear() != cal.sYear) { sd = 1; }
    else { sd = sd.getMonth()+1 < cal.sMth ? 1 : sd.getDate(); }
    if (ed.getFullYear() != cal.sYear) { ed = daysInMth; }
    else { ed = ed.getMonth()+1 > cal.sMth ? daysInMth : ed.getDate(); }
 
    // (G3-2) "MAP" ONTO HTML CALENDAR
    cell = {}; rowNum = 0;
    for (let i=sd; i<=ed; i++) {
      if (rowNum!=rowMap[i]["r"]) {
        cell[rowMap[i]["r"]] = { s:rowMap[i]["c"], e:0 };
        rowNum = rowMap[i]["r"];
      }
      if (cell[rowNum]) { cell[rowNum]["e"] = rowMap[i]["c"]; }
    }
 
    // (G3-3) DRAW HTML EVENT ROW
    for (let [r,c] of Object.entries(cell)) {
      let o = c.s - 1 - ((r-1) * 7), // event cell offset
          w = c.e - c.s + 1; // event cell width
      rowA = document.getElementById("calRow"+r);
      rowB = document.createElement("div");
      rowB.className = "calRowEvt";
      rowB.innerHTML = cal.events[id]["t"];
      rowB.style.color = cal.events[id]["c"];
      rowB.style.backgroundColor = cal.events[id]["b"];
      rowB.classList.add("w"+w);
      if (o!=0) { rowB.classList.add("o"+o); }
      rowB.onclick = () => cal.show(id);
      rowA.appendChild(rowB);
    }
  }}
},

I know, it’s massive. But all cal.draw() actually does is get data from 3-cal-ajax.php and generate the calendar HTML.

 

4E) JAVASCRIPT CALENDAR EVENTS

4b-calendar.js
// (H) SHOW EVENT FORM
show : id => {
  if (id) {
    cal.hfID.value = id;
    cal.hfStart.value = cal.events[id]["s"].replace(" ", "T").substring(0, 16);
    cal.hfEnd.value = cal.events[id]["e"].replace(" ", "T").substring(0, 16);
    cal.hfTxt.value = cal.events[id]["t"];
    cal.hfColor.value = cal.events[id]["c"];
    cal.hfBG.value = cal.events[id]["b"];
    cal.hfDel.style.display = "inline-block";
  } else {
    cal.hForm.reset();
    cal.hfID.value = "";
    cal.hfDel.style.display = "none";
  }
  if (document.startViewTransition) { document.startViewTransition(() => cal.hFormWrap.show()); }
  else { cal.hFormWrap.show(); }
},
 
// (I) SAVE EVENT
save : () => {
  // (I1) COLLECT DATA
  var data = {
    req : "save",
    start : cal.hfStart.value,
    end : cal.hfEnd.value,
    txt : cal.hfTxt.value,
    color : cal.hfColor.value,
    bg : cal.hfBG.value
  };
  if (cal.hfID.value != "") { data.id = cal.hfID.value; }
 
  // (I2) DATE CHECK
  if (new Date(data.start) > new Date(data.end)) {
    alert("Start date cannot be later than end date!");
    return false;
  }
 
  // (I3) AJAX SAVE
  cal.ajax(data, res => { if (res == "OK") {
    cal.hFormWrap.close();
    cal.draw();
  } else { alert(res); }});
  return false;
},
 
// (J) DELETE EVENT
del : () => { if (confirm("Delete event?")) {
  cal.ajax({
    req : "del", id : cal.hfID.value
  }, res => { if (res == "OK") {
    cal.hFormWrap.close();
    cal.draw();
  } else { alert(res); }});
}}

The last few sections of the Javascript deal with calendar events.

  • cal.show() Show the add/edit event form.
  • cal.save() Save the event.
  • cal.del() Delete the event.

 

PART 5) PROGRESSIVE WEB APP

 

5A) HTML META HEADERS

4a-cal-page.php
<!-- ANDROID + CHROME + APPLE + WINDOWS APP -->
<meta name="mobile-web-app-capable" content="yes">
<meta name="theme-color" content="white">
<link rel="apple-touch-icon" href="icon-512.png">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Calendar">
<meta name="msapplication-TileImage" content="icon-512.png">
<meta name="msapplication-TileColor" content="#ffffff">
 
<!-- WEB APP MANIFEST -->
<!-- https://web.dev/add-manifest/ -->
<link rel="manifest" href="5-manifest.json">
 
<!-- SERVICE WORKER -->
<script>
if ("serviceWorker" in navigator) {
  navigator.serviceWorker.register("5-worker.js");
}
</script>

The system is already complete and this is completely optional. But to turn this into a progressive web app, all it requires are 3 things:

  • Add some “web app” meta tags in the HTML head section. I am too lazy to resize the icons and set the colors properly… Change these in your own free time if you want.
  • Add a web app manifest.
  • Register a service worker.

 

5B) WEB MANIFEST

5-manifest.json
{
  "short_name": "Calendar",
  "name": "Calendar",
  "icons": [{
     "src": "favicon.png",
     "sizes": "64x64",
     "type": "image/png"
  }, {
    "src": "icon-512.png",
    "sizes": "512x512",
    "type": "image/png"
  }],
  "start_url": "/4a-cal-page.php",
  "scope": "/",
  "background_color": "white",
  "theme_color": "white",
  "display": "standalone"
}

The manifest file is what it is, a file that contains information about your web app – App name, icons, theme, settings, etc…

 

5C) SERVICE WORKER

5-worker.js
// (A) CREATE/INSTALL CACHE
self.addEventListener("install", evt => {
  self.skipWaiting();
  evt.waitUntil(
    caches.open("phpcal")
    .then(cache => cache.addAll([
      "4b-calendar.js",
      "4c-calendar.css",
      "5-manifest.json",
      "favicon.png",
      "icon-512.png"
    ]))
    .catch(err => console.error(err))
  );
});
 
// (B) CLAIM CONTROL INSTANTLY
self.addEventListener("activate", evt => self.clients.claim());

// (C) LOAD FROM CACHE FIRST, FALLBACK TO NETWORK IF NOT FOUND
self.addEventListener("fetch", evt => evt.respondWith(
  caches.match(evt.request).then(res => res || fetch(evt.request))
));

For those who are new – A service worker is simply Javascript that runs in the background. For this service worker:

  • (A) We create a browser cache and save the CSS/JS.
  • (C) Hijack the fetch requests. If the requested file is found in the cache, use it. If not, fall back to load from the network.

In other words, this service worker speeds up loading and lessens the server load.

 

EXTRAS

That’s it for the tutorial and here are some small extras that you may find useful.

 

COMPATIBILITY CHECKS

This example will work on most modern “Grade A” browsers.

 

IMPROVEMENT IDEAS & LIMITATIONS

Yes, this is a fully functioning simple events calendar system. But there are plenty of improvements that you can make, plus some limitations to take note of:

  • The system is open to all users – You will want to integrate your own user login and protection.
  • If sensitive information is involved, it is best to encrypt it.
  • Only one calendar instance per page. Please stop asking “how to put multiple instances on the same page”, there is no easy way… Feel free to challenge yourself though.
  • May look a little squished on portrait-mode smartphones. A possible fix is to allow an “ugly horizontal scrollbar on the calendar”.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to build a better project, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!

82 thoughts on “Simple Events Calendar With PHP MySQL (Free Code Download)”

  1. Hello.
    Great calendar, just one question.
    Is there an easy way to create vertical and horizontal lines so each date number is in a cell?

  2. Hello and thanks for the great work with the calendar.

    How can I do to be able to modify the link in the calendar (the one that opens the insertion/modification form), because I would like to do (on my cms with multi-user access) so that based on the user who has inserted, allow or not to edit or delete the event.
    In practice, only those who entered that event can modify or cancel it.
    But I can’t find the part in the js where it generates the link.

    Hello and thanks

    1. As above –
      1) Add user ID to database table.
      2) Modify library functions to include user ID, check user ID before processing.
      3) Start user session in AJAX handler, pass user ID into library functions.

      The end. There’s no need to change the HTML/Javascript.

    2. Hello and thanks
      I added the id to the database (all very clear so far).
      Instead I can’t figure out where I have to go to work in the library file (2-cal-lib.php), unfortunately my js and ajax level is very low….
      Even in the 3-cal-ajax.php file I can’t figure out where to change.

      Don’t you have paid tickets for solving very difficult problems? 😀

  3. In order for the calendar to start on Monday, you need to use 4b-calendar.js change mon: false, to true.
    The manual mistakenly says that changes need to be made to 2-cal-lib.php

  4. Hi, thanks for the beautiful & functional calendar tutorial.
    Can you help give me a tips, if i want to add additional fields to the form, which file should i modify?

    thanks in advance

    1. As above?

      Part 1) Add more fields to the database table if required.
      Part 2) Update the PHP library functions with new fields.
      Part 3) Update AJAX handler.
      Part 4) Update HTML/JS user interface.

  5. Maybe it’s my fault, maybe a bug, but if i add a multiple-day event at the end of the year with startdate in year X and enddate in year X+1, the DB entry is saved, but the page does not show it.

Leave a Comment

Your email address will not be published. Required fields are marked *