Build an Event Calendar with PHP using jQuery, Ajax, and MySQL

Event calendar provides a user-friendly way to list events by dates. It helps the user to find the events quickly for a specific date. The event calendar is a very useful element to display events datewise in a user-friendly way on the web application. There are various jQuery plugins are available to integrate the event calendar on the website. But if you want to list events dynamically on the large calendar, the event calendar is the best option and it can be easily implemented using PHP.

PHP Event Calendar helps to fetch the dynamic data from the database and list events in the date cell of the calendar. Using the PHP event calendar you can add the event to the calendar along with the respective date. In this tutorial, we will show you how to create an event calendar using jQuery, Ajax, PHP, and MySQL.

The following functionality will be implemented to build event calendar with PHP.

  • Fetch events data from the MySQL database.
  • Create a large calendar with HTML and CSS.
  • Display events in the date cell of the calendar.
  • Navigate between the months and years using jQuery and Ajax.

Before getting started, take a look 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 in the calendar, the event data need to be stored in the database. The following SQL creates an events table with some basic fields in 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 used to connect 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 "root";
$dbName     "codexworld";

// 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 Build Event Calendar (functions.php)

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

  • getCalender()
    • Generate calendar based on the specific month and year.
    • Fetch events from the database and add the events to the date cell of the calendar.
  • getMonthList() – Create months option list for the select box which is used for months dropdown.
  • getYearList() – Create years option list for the select box which is used for years dropdown.
  • getEvents() – Fetch events by date from 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%== && $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(000$i+100)).'</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 web page.

  • Include the file of the helper functions (functions.php).
  • Use getCalender() function to add calendar in the web page.
  • AJAX request is used 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 CodexWorld</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 like the below screen. The events counter will be listed under each day of the calendar. On the left side of the calendar, today’s date and all the events will be listed.

  • The desired month and year can be changed from the top of the event calendar.
  • By changing the year, month, and date, the respective events will be loaded without page refresh using jQuery and Ajax.
php-large-event-calendar-jquery-ajax-mysql-codexworld

Conclusion

This example large calendar code provides a quick and easy way to integrate a dynamic event calendar with PHP and MySQL. The jQuery and Ajax are used to load the events without page refresh on the date change. This event calendar can be used for many purposes, like booking calendar, holiday calendar, etc. You can easily build a user-friendly event calendar using jQuery, Ajax, PHP, and MySQL. Our next tutorial on PHP Event calendar will show you how to add events to the calendar using jQuery, Ajax, PHP, and MySQL.

Add Event to Calendar using jQuery, Ajax and PHP

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

59 Comments

  1. ERIC W Said...
  2. Ivan Pereira Said...
  3. Luis Palma Said...
  4. Mike May Said...

Leave a reply

keyboard_double_arrow_up