Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

3 Steps to Build a Simple PHP Calendar (With Events)

INTRODUCTION
GET ORGANIZED

Welcome to a tutorial on how to build an AJAX-driven simple PHP calendar with events. Looking to add some organization features to you own project? No worries, you have come to the right place, and this guide will walk you through how to create a simple calendar, step-by-step. Read on!

I have included a zip file with all the source code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!

NAVIGATION
TABLE OF CONTENTS

Prelude
Before We Start

Step 1
Database

Step 2
Server-side Scripts

Step 3
Client-side Scripts

Extra
Download & More

Closing
What’s Next?

PRELUDE
BEFORE WE START

Before we dive into the scripts, here is a small section on the system overview, and some assumptions plus things to expect from this tutorial.

ASSUMPTIONS

A standalone calendar will not really make a lot of sense. So I am assuming that you guys already have an existing project, and want to build a calendar on top of it – That you guys are already code ninjas, comfortable with the basics, and I won’t have to go into every tiny detail of “how it works”.

SYSTEM OVERVIEW

There are 3 parts to this simple calendar system:

  • A database table to store all the event entries.
  • Library files, server-side scripts that will save and retrieve data from the database.
  • Client-side scripts, which is the HTML user interface.

STEP 1
DATABASE

Let us start by dealing with the foundation of the system – The database. Not to worry, this is nothing but a very simple table with only 2 fields.

EVENTS TABLE

calendar.sql
CREATE TABLE `events` (
  `date` date NOT NULL,
  `details` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8

ALTER TABLE `events`
  ADD PRIMARY KEY (`date`);
FieldDescription
dateThe event date, primary key.
detailsThe event details.

STEP 2
SERVER-SIDE SCRIPTS

Now that we have established the database, let us move on to the next part of the foundation – Server-side scripts that will work with the database and process AJAX requests.

CONFIG FILE

config.php

Let us start by creating a config file to contain the database settings – remember to change these to your own. Apart from that, there is nothing special with it. Just take note that I have also muted the notice reporting here – Those are non-critical “error messages” that are naggy, will not break the system, and only serve to scare the beginners away.

DATABASE LIBRARY

lib-db.php
pdo = new PDO(
        $str, DB_USER, DB_PASSWORD, [
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
          PDO::ATTR_EMULATE_PREPARES => false
        ]
      );
      return true;
    }

    // ERROR - DO SOMETHING HERE
    // THROW ERROR MESSAGE OR SOMETHING
    catch (Exception $ex) {
      print_r($ex);
      die();
    }
  }

  function __destruct() {
  // __destruct() : close connection when done

    if ($this->stmt !== null) { $this->stmt = null; }
    if ($this->pdo !== null) { $this->pdo = null; }
  }

  function exec($sql, $data=null) {
  // exec() : run insert, replace, update, delete query
  // PARAM $sql : SQL query
  //       $data : array of data
 
    try {
      $this->stmt = $this->pdo->prepare($sql);
      $this->stmt->execute($data);
      $this->lastID = $this->pdo->lastInsertId();
    } catch (Exception $ex) {
      $this->error = $ex;
      return false;
    }
    $this->stmt = null;
    return true;
  }

  function fetch($sql, $cond=null, $key=null, $value=null) {
  // fetch() : perform select query
  // PARAM $sql : SQL query
  //       $cond : array of conditions
  //       $key : sort in this $key=>data order, optional
  //       $value : $key must be provided, sort in $key=>$value order

    $result = false;
    try {
      $this->stmt = $this->pdo->prepare($sql);
      $this->stmt->execute($cond);
      if (isset($key)) {
        $result = array();
        if (isset($value)) {
          while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) {
            $result[$row[$key]] = $row[$value];
          }
        } else {
          while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) {
            $result[$row[$key]] = $row;
          }
        }
      } else {
        $result = $this->stmt->fetchAll();
      }
    } catch (Exception $ex) {
      $this->error = $ex;
      return false;
    }
    $this->stmt = null;
    return $result;
  }
}
?>

This is the library that will work with the database, actually from my other tutorial. Read it if you are interested to know more.

5 Simple PHP Database Examples (Beginner’s Guide)

FunctionDescription
__constructContstructor, automatically connects to the database when the object is created.
__destructDestructor, automatically closes the database connection when the object is destroyed.
execRuns an insert, replace update, or delete SQL statement.
fetchRuns a select query.

CALENDAR LIBRARY

lib-calendar.php
fetch($sql, [$date]);
    return count($evt)==0 ? false : $evt[0]['details'] ;
  }

  function getRange($start, $end) {
  // getRange() : get all events in between selected date range
  // PARAM $start : start date
  //       $end : end date
 
    $sql = "SELECT * FROM `events` WHERE `date` BETWEEN ? AND ?";
    $evt = $this->fetch($sql, [$start, $end], "date", "details");
    return count($evt)==0 ? false : $evt ;
  }

  function save($date, $details) {
  // save() : create/update event on specified date
  // PARAM $date : date
  //       $details : event details
 
    $sql = "REPLACE INTO `events` (`date`, `details`) VALUES (?, ?)";
    return $this->exec($sql, [$date, $details]);
  }

  function delete($date) {
  // delete() : delete event on specified date
  // PARAM $date : date
 
    $sql = "DELETE FROM `events` WHERE `date`=?";
    return $this->exec($sql, [$date]);
  }
}
?>

With the database library, we can now build another library for the calendar… Which is pretty much just some SQL.

FunctionDescription
getGet event for the specified date.
getRangeGet events for the specified date range.
saveSave event to the database table.
deleteDelete an event.

AJAX HANDLER

ajax-calendar.php
getRange($ym."01", $ym.$daysInMonth);

    // DRAWING CALCULATION
    // Determine the number of blank squares before start of month
    $squares = [];
    if ($firstDayOfMonth != 7) {
      for ($i=0; $i
    ";
          } else {
            $fullDay = sprintf("%s%02u", $ym, $thisDay);
            printf("", 
              $fullDay, $thisDay,
              $events[$fullDay] ? "
" . $events[$fullDay] . "
" : "" ); } if ($i!=$total && $i%7==0) { echo ""; } } ?>
Sun Mon Tue Wed Thur Fri Sat
%s%s
get($_POST['date']); ?>

=$evt==false?"ADD":"EDIT"?> EVENT

=$_POST['date']?>
save($_POST['date'], $_POST['details']) ? "OK" : "ERR" ; break; /* [DELETE EVENT] */ case "del" : echo $calLib->delete($_POST['date']) ? "OK" : "ERR" ; break; } ?>

Remember that this is an AJAX-driven application? That is why we are building an AJAX handler that will do all the processing. How it works is very simple, just post the service in $_POST['req'] that you need, followed by the required parameters.

RequestDescription
listShows calendar for the specified month and year.

Parameters: month (Jan-Dec), year (YYYY).

showShow add/edit event docket for the specified date.

Parameters: date (YYYY-MM-DD).

saveSave event for the specified date.

Parameters: date (YYYY-MM-DD), details.

delDelete event for the specified date.

Parameters: date (YYYY-MM-DD).

STEP 3
CLIENT-SIDE SCRIPTS

That’s it, we have now established all the required foundations. For this final step, all that is left is to build the user interface.

THE LANDING PAGE

index.php
Simple PHP Calendar

The landing page should be pretty straightforward:

  • At the top of the page is the month/year selector – Which defaults to the current time on the server.
  • In the middle is a container that we will load the calendar into (via AJAX).
  • At the bottom is yet another container that we will load the add/edit event docket into, after we click on a day in the calendar.

CSS

theme.css
/* [SITE] */
html, body, textarea, input{
  font-family: arial;
}
 
/* [PERIOD SELECTOR] */
#selector{
  padding: 10px;
}
#selector select, #selector input[type=button]{
  padding: 10px;
  font-size: 1.2em;
}

/* [CALENDAR] */
#calendar{
  width: 100%;
  border-collapse: collapse;
}
#calendar tr td{
  border: 1px solid #ccc;
  padding: 20px 5px;
  width: 14.28%;
  vertical-align: top;
}
td.blank{
  background: #eee;
}
tr.day td{
  background: #ba3423;
  color: #fff;
  font-weight: bold;
}
.evt{
  margin-top: 5px;
  padding: 5px;
  background: #fff2dd;
  color: #555;
  font-size: 0.75em;
  max-height: 5em;
  overflow: hidden;
}

/* [ADD/EDIT EVENT] */
#event form{
  margin-top: 10px;
  padding: 10px;
  background: #f2f2f2;
}
#event h1{
  padding: 0;
  margin: 0;
}
#evt-date{
  margin: 10px 0;
  font-weight: bold;
}
#event textarea{
  display: block;
  padding: 10px;
  margin: 10px 0;
  min-width: 320px;
  resize: none;
}
#event input[type=button], #event input[type=submit]{
  padding: 10px;
  font-size: 1.05em;
}

This rather complex looking script is nothing more than just some cosmetics… Feel free to change it to fit your own project.

JAVASCRIPT

calendar.js
var cal = {
  list: function () {
  // list() : show calendar for selected month & year

    // DATA
    var data = new FormData();
    data.append('req', 'list');
    data.append('month', document.getElementById("month").value);
    data.append('year', document.getElementById("year").value);

    // AJAX
    var xhr = new XMLHttpRequest();
    xhr.open('POST', "ajax-calendar.php", true);
    xhr.onload = function () {
      document.getElementById("event").innerHTML = "";
      document.getElementById("container").innerHTML = this.response;
    };
    xhr.send(data);
  },

  show: function(day) {
  // show() : show event for selected day
  // PARAM day : selected date

    // DATA
    var data = new FormData();
    data.append('req', 'show');
    data.append('date', day);

    // AJAX
    var xhr = new XMLHttpRequest();
    xhr.open('POST', "ajax-calendar.php", true);
    xhr.onload = function () {
      document.getElementById("event").innerHTML = this.response;
    };
    xhr.send(data);
  },

  save: function() {
  // save() : save event for selected day

    // DATA
    var data = new FormData();
    data.append('req', 'save');
    data.append('date', document.getElementById('evt-date').innerHTML);
    data.append('details', document.getElementById('evt-details').value);

    // AJAX
    var xhr = new XMLHttpRequest();
    xhr.open('POST', "ajax-calendar.php", true);
    xhr.onload = function(){
      if (this.response=="OK") {
        cal.list();
      } else {
        alert("Error saving event");
      }
    };
    xhr.send(data);
    return false;
  },

  del: function() {
  // del() : delete event for selected day

    if (confirm("Delete event?")) {
      // DATA
      var data = new FormData();
      data.append('req', 'del');
      data.append('date', document.getElementById('evt-date').innerHTML);

      // AJAX
      var xhr = new XMLHttpRequest();
      xhr.open('POST', "ajax-calendar.php", true);
      xhr.onload = function(){
        if (this.response=="OK") {
          cal.list();
        } else {
          alert("Error deleting event");
        }
      };
      xhr.send(data);
    }
  }
};

window.addEventListener("load", cal.list);

Finally, we have the Javascript that does most of the actual heavy weight lifting… But actually, even though all of these look complicated – they are just a bunch of AJAX calls.

FunctionDescription
listShows the calendar for the selected month and year.
showShow the add/edit event docket for the selected day.
saveSave the event for the selected day.
delDelete event for the selected day.

EXTRA
DOWNLOAD & MORE

That’s it for all the code, and here is the download link plus a small extra that you may find useful.

LIMITATIONS

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

  • The current design only accepts one event a day.
  • Events cannot span event across many days.
  • The system is open to all users without protection – You will want to integrate some form of user identification and security.

You can further upgrade the events it if you want, give it a start and end date… Although that will add quite a lot more to the complexity, and you will have to figure out how to determine if events have ended for a selected period of time.

DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

CLOSING
WHAT’S NEXT?

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


The post 3 Steps to Build a Simple PHP Calendar (With Events) appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

3 Steps to Build a Simple PHP Calendar (With Events)

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×