Event calendar provides a user-friendly thanks to list events by dates. It helps the user to find the events quickly for a selected date. The event calendar may be a very useful element to display events date wise during a user-friendly way on the online application. There are various jQuery plugins are available to integrate the event calendar on the web site. But if you would like to list events dynamically on the large calendar, the event calendar is that the best choice and it can be easily implemented using PHP.

PHP Event Calendar helps to fetch the dynamic data from the database and list events within the date cell of the calendar. Using the PHP event calendar you’ll add the event to the calendar alongside the respective date. During this tutorial, we’ll show you ways to make an event calendar using jquery, Ajax, PHP, and MYSQL.

 

The following functionality is going to be implemented to create event calendar with PHP.

  • Fetch events data from the MYSQL database.
  • Create an outsized calendar with HTML and CSS.
  • Display events within the date cell of the calendar.
  • Navigate between the months and years using jquery and Ajax.
  • Before getting started, take a glance at the file structure of the PHP event calendar script.

Php_event_calendar/

├── index.php

├── functions.php

├── dbconfig.php

├── js/

│   └── jquery.min.js

└── css/

└── style.css

Create Database Table

To display the dynamic events within the calendar, the event data got to be stored within the database. The following SQL creates an events table with some basic fields within the MYSQL database.

CREATE TABLE `events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`date` date NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
PRIMARY KEY (`id`)
) ENGINE=innodb DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbconfig.php)

This file is employed to attach with the database using PHP and MYSQL. Specify the database host ($dbhost), username ($dbusername), password ($dbpassword), and name ($dbname) as per your database credentials.

<?Php 
// Database configuration
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "pwd";
$dbname = "gpkumar";

// Create database connection
$db = new mysqli($dbhost, $dbusername, $dbpassword, $dbname);

// Check connection
If ($db->connect_error) {
Die("Connection failed: " . $db->connect_error);
}

Helper Functions to create Event Calendar (functions.php)

The functions.php file holds all the functions that are used to generate an event calendar with PHP and MYSQL.

  1. Getcalender() –
  • Generate calendar supported the precise month and year.
  • Fetch events from the database and add the events to the date cell of the calendar.
  1. Getmonthlist() – Create months option list for the select box which is employed for months dropdown.
  2. Getyearlist() – Create years option list for the select box which is employed for years dropdown.
  3. Getevents() – Fetch events by go back the database and returns the events list as HTML format.
<?Php 
// Include the database config file
Include_once 'dbconfig.php';

/*
* Load function based on the Ajax request
*/
If(isset($_POST['func']) && !Empty($_POST['func'])){
Switch($_POST['func']){
Case 'getcalender':
Getcalender($_POST['year'],$_POST['month']);
Break;
Case 'getevents':
Getevents($_POST['date']);
Break;
Default:
Break;
}
}

/*
* Generate event calendar in HTML format
*/
Function getcalender($year = '', $month = ''){
$dateyear = ($year != '')?$year:date("Y");
$datemonth = ($month != '')?$month:date("m");
$date = $dateyear.'-'.$datemonth.'-01';
$currentmonthfirstday = date("N",strtotime($date));
$totaldaysofmonth = cal_days_in_month(CAL_GREGORIAN,$datemonth,$dateyear);
$totaldaysofmonthdisplay = ($currentmonthfirstday == 1)?($totaldaysofmonth):($totaldaysofmonth + ($currentmonthfirstday - 1));
$boxdisplay = ($totaldaysofmonthdisplay <= 35)?35:42;

$prevmonth = date("m", strtotime('-1 month', strtotime($date)));
$prevyear = date("Y", strtotime('-1 month', strtotime($date)));
$totaldaysofmonth_Prev = cal_days_in_month(CAL_GREGORIAN, $prevmonth, $prevyear);
?>
<main class="calendar-contain">
<section class="title-bar">
<a href="javascript:void(0);" class="title-bar__prev" onclick="getcalendar('calendar_div','<?Php echo date("Y",strtotime($date.' - 1 Month')); ?>','<?Php echo date("m",strtotime($date.' - 1 Month')); ?>');"></a>
<div class="title-bar__month">
<select class="month-dropdown">
<?Php echo getmonthlist($datemonth); ?>
</select>
</div>
<div class="title-bar__year">
<select class="year-dropdown">
<?Php echo getyearlist($dateyear); ?>
</select>
</div>
<a href="javascript:void(0);" class="title-bar__next" onclick="getcalendar('calendar_div','<?Php echo date("Y",strtotime($date.' + 1 Month')); ?>','<?Php echo date("m",strtotime($date.' + 1 Month')); ?>');"></a>
</section>

<aside class="calendar__sidebar" id="event_list">
<?Php echo getevents(); ?>
</aside>

<section class="calendar__days">
<section class="calendar__top-bar">
<span class="top-bar__days">Mon</span>
<span class="top-bar__days">Tue</span>
<span class="top-bar__days">Wed</span>
<span class="top-bar__days">Thu</span>
<span class="top-bar__days">Fri</span>
<span class="top-bar__days">Sat</span>
<span class="top-bar__days">Sun</span>
</section>

<?Php
$daycount = 1;
$eventnum = 0;

Echo '<section class="calendar__week">';
For($cb=1;$cb<=$boxdisplay;$cb++){
If(($cb >= $currentmonthfirstday || $currentmonthfirstday == 1) && $cb <= ($totaldaysofmonthdisplay)){
// Current date
$currentdate = $dateyear.'-'.$datemonth.'-'.$daycount;

// Get number of events based on the current date
Global $db;
$result = $db->query("SELECT title FROM events WHERE date = '".$currentdate."' AND status = 1");
$eventnum = $result->num_rows;

// Define date cell color
If(strtotime($currentdate) == strtotime(date("Y-m-d"))){
Echo '
<div class="calendar__day today" onclick="getevents(\''.$currentdate.'\');">
<span class="calendar__date">'.$daycount.'</span>
<span class="calendar__task calendar__task--today">'.$eventnum.' Events</span>
</div>
';
}elseif($eventnum > 0){
Echo '
<div class="calendar__day event" onclick="getevents(\''.$currentdate.'\');">
<span class="calendar__date">'.$daycount.'</span>
<span class="calendar__task">'.$eventnum.' Events</span>
</div>
';
}else{
Echo '
<div class="calendar__day no-event" onclick="getevents(\''.$currentdate.'\');">
<span class="calendar__date">'.$daycount.'</span>
<span class="calendar__task">'.$eventnum.' Events</span>
</div>
';
}
$daycount++;
}else{
If($cb < $currentmonthfirstday){
$inactivecalendarday = ((($totaldaysofmonth_Prev-$currentmonthfirstday)+1)+$cb);
$inactivelabel = 'expired';
}else{
$inactivecalendarday = ($cb-$totaldaysofmonthdisplay);
$inactivelabel = 'upcoming';
}
Echo '
<div class="calendar__day inactive">
<span class="calendar__date">'.$inactivecalendarday.'</span>
<span class="calendar__task">'.$inactivelabel.'</span>
</div>
';
}
Echo ($cb%7 == 0 && $cb != $boxdisplay)?'</section><section class="calendar__week">':'';
}
Echo '</section>';
?>
</section>
</main>

<script>
Function getcalendar(target_div, year, month){
$.ajax({
Type:'POST',
Url:'functions.php',
Data:'func=getcalender&year='+year+'&month='+month,
Success:function(html){
$('#'+target_div).html(html);
}
});
}

Function getevents(date){
$.ajax({
Type:'POST',
Url:'functions.php',
Data:'func=getevents&date='+date,
Success:function(html){
$('#event_list').html(html);
}
});
}

$(document).ready(function(){
$('.month-dropdown').on('change',function(){
Getcalendar('calendar_div', $('.year-dropdown').val(), $('.month-dropdown').val());
});
$('.year-dropdown').on('change',function(){
Getcalendar('calendar_div', $('.year-dropdown').val(), $('.month-dropdown').val());
});
});
</script>
<?Php
}

/*
* Generate months options list for select box
*/
Function getmonthlist($selected = ''){
$options = '';
For($i=1;$i<=12;$i++)
{
$value = ($i < 10)?'0'.$i:$i;
$selectedopt = ($value == $selected)?'Selected':'';
$options .= '<option value="'.$value.'" '.$selectedopt.' >'.date("F", mktime(0, 0, 0, $i+1, 0, 0)).'</option>';
}
Return $options;
}

/*
* Generate years options list for select box
*/
Function getyearlist($selected = ''){
$yearinit = !Empty($selected)?$selected:date("Y");
$yearprev = ($yearinit - 5);
$yearnext = ($yearinit + 5);
$options = '';
For($i=$yearprev;$i<=$yearnext;$i++){
$selectedopt = ($i == $selected)?'Selected':'';
$options .= '<option value="'.$i.'" '.$selectedopt.' >'.$i.'</option>';
}
Return $options;
}

/*
* Generate events list in HTML format
*/
Function getevents($date = ''){
$date = $date?$date:date("Y-m-d");

$eventlisthtml = '<h2 class="sidebar__heading">'.date("l", strtotime($date)).'<br>'.date("F d", strtotime($date)).'</h2>';

// Fetch events based on the specific date
Global $db;
$result = $db->query("SELECT title FROM events WHERE date = '".$date."' AND status = 1");
If($result->num_rows > 0){
$eventlisthtml .= '<ul class="sidebar__list">';
$eventlisthtml .= '<li class="sidebar__list-item sidebar__list-item--complete">Events</li>';
$i=0;
While($row = $result->fetch_assoc()){ $i++;
$eventlisthtml .= '<li class="sidebar__list-item"><span class="list-item__time">'.$i.'.</span>'.$row['title'].'</li>';
}
$eventlisthtml .= '</ul>';
}
Echo $eventlisthtml;
}

Display Event Calendar (index.php)

Call the getcalender() function to display the event calendar on the online page.

  • Include the file of the helper functions (functions.php).
  • Use getcalender() function to feature calendar within the website .
  • AJAX request is employed to load the respective events on date change, so, include the jquery library.
<?Php 
// Include calendar helper functions
Include_once 'functions.php';
?>

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>PHP Event Calendar by Gpkumar.com</title>
<meta charset="utf-8">

<!-- Stylesheet file -->
<link rel="stylesheet" href="css/style.css">

<!-- jquery library -->
<script src="js/jquery.min.js"></script>
</head>
<body>
<!-- Display event calendar -->
<div id="calendar_div">
<?Php echo getcalender(); ?>
</div>
</body>
</html>

Testing

Once you called the getcalender() function on the webpage, a large calendar will appear as if the below screen. The events counter is going to be listed under every day of the calendar. On the left side of the calendar, today’s date and every one the events are going to be listed.

  • The desired month and year is changed from the highest of the event calendar.
  • By changing the year, month, and date, the respective events are going to be loaded without page refresh using jQuery and Ajax.

Conclusion

This example large calendar code provides a fast and easy thanks to integrate a dynamic event calendar with PHP and MYSQL. The jQuery and Ajax are wont to load the events without page refresh on the date change. This event calendar is often used for several purposes, like booking calendar, holiday calendar, etc. You’ll easily build a user-friendly event calendar using jQuery, Ajax, PHP, and MYSQL. Our next tutorial on PHP Event calendar will show you ways to feature events to the calendar using jQuery, Ajax, PHP, and MYSQL.

Categorized in: