Skip to Content
PHPCODE
CodeIgniter booking calendar
php code / September 18, 2021

The Event Calendar aids in the user-friendly listing of events from the database. The full view calendar is the greatest solution for dynamically displaying events in a calendar. The events are retrieved from the database and shown in the huge calendar in the dynamic web application. PHP and MySQL make it simple to create a dynamic event calendar.

The event calendar functionality must be integrated into the CodeIgniter application if your web application is built with the CodeIgniter framework. In CodeIgniter, you can quickly design a custom event calendar to display events from the database. In this article, we’ll teach you how to use jQuery and Ajax to create an event calendar in CodeIgniter.

The following functionality will be provided in the CodeIgniter Event Calendar sample.

Get data from the MySQL database about events.
Using HTML and CSS, create a full-view calendar.
Display events in the calendar’s date cell.
Using jQuery and Ajax, switch between months and years.
Take a look at the file structure before you start writing an event calendar script in CodeIgniter.

codeigniter_event_calendar/
├── application/
│   ├── controllers/
│   │   └── Calendar.php
│   ├── models/
│   │   └── Event.php
│   └── views/
│       └── calendar/
│           ├── index.php
│           └── event-cal.php
└── assets/
    ├── js/
    │   └── jquery.min.js
    └── css/
        └── style.css

Make a database table.
A table in the database is required to store the dynamic events data. In the MySQL database, the following SQL creates an events table with some basic fields.

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;

the supervisor (Calendar.php)
The Calendar controller aids in the generation of event calendars as well as the presentation of calendars in full view.

Load the Event model with __construct().
index() – Get the eventCalendar() method’s calendar.
The calendar HTML should be passed to the view.
Build an event calendar based on the year and month with eventCalendar().
View the calendar in a new window.
getMonths() – Creates a list of months to choose from in the select box.
getYears() – Creates a list of year alternatives for the pick box.
getEvents() — Using the Event model’s getRows() method, fetch events from the database.
Create an HTML version of the event schedules.

<?php defined('BASEPATH') OR exit('No direct script access allowed'); 
class Calendar extends CI_Controller { 
function __construct() { 
parent::__construct(); 

$this->load->model('event'); 
} 
public function index(){ 
$data = array(); 
$data['eventCalendar'] = $this->eventCalendar(); 
$this->load->view('calendar/index', $data); 
} 
/* 
* Generate calendar with events 
*/ 
public function eventCalendar($year = '', $month = ''){ 
$data = array(); 
$dateYear = ($year != '')?$year:date("Y"); 
$dateMonth = ($month != '')?$month:date("m"); 
$date = $dateYear.'-'.$dateMonth.'-01'; 
$eventDate = empty($year) && empty($month)?date("Y-m-d"):$date; 
$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); 
$con = array( 
'where' => array( 
'status' => 1 
), 
'where_year' => $dateYear, 
'where_month' => $dateMonth 
); 
$data['events'] = $this->event->getGroupCount($con); 
$data['calendar'] = array( 
'dateYear' => $dateYear, 
'dateMonth' => $dateMonth, 
'date' => $date, 
'currentMonthFirstDay' => $currentMonthFirstDay, 
'totalDaysOfMonthDisplay' => $totalDaysOfMonthDisplay, 
'boxDisplay' => $boxDisplay, 
'totalDaysOfMonth_Prev' => $totalDaysOfMonth_Prev 
); 
$data['monthOptions'] = $this->getMonths($dateMonth); 
$data['yearOptions'] = $this->getYears($dateYear); 
$data['eventList'] = $this->getEvents($eventDate, 'return'); 
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH'])){ 
$this->load->view('calendar/event-cal', $data); 
}else{ 
return $this->load->view('calendar/event-cal', $data, true); 
} 
} 
/* 
* Generate months options list for select box 
*/ 
function getMonths($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 getYears($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 = '', $return='view'){ 
$date = $date?$date:date("Y-m-d"); 
// Fetch events based on the specific date 
$con = array( 
'where' => array( 
'date' => $date, 
'status' => 1 
) 
); 
$events = $this->event->getRows($con); 
$eventListHTML = '<h2 class="sidebar__heading">'.date("l", strtotime($date)).'<br>'.date("F d, Y", strtotime($date)).'</h2>'; 
if(!empty($events)){ 
$eventListHTML .= '<ul class="sidebar__list">'; 
$eventListHTML .= '<li class="sidebar__list-item sidebar__list-item--complete">Events</li>'; 
$i = 0; 
foreach($events as $row){ $i++; 
$eventListHTML .= '<li class="sidebar__list-item"><span class="list-item__time">'.$i.'.</span>'.$row['title'].'</li>'; 
} 
$eventListHTML .= '</ul>'; 
} 
if($return == 'return'){ 
return $eventListHTML; 
}else{ 
echo $eventListHTML; 
} 
} 
}

Modeling (Event.php)
The database operations are handled by the Event model.

Define the table name with __construct().
getRows() – Retrieves the events data from the database depending on the $params requirements. If successful, returns the data array; if unsuccessful, returns FALSE.
getGroupCount() – Returns data containing event numbers for each date, grouped by events based on the date.

<?php defined('BASEPATH') OR exit('No direct script access allowed'); 
class Event extends CI_Model{ 
function __construct() { 
// Set table name 
$this->table = 'events'; 
} 
/* 
* Fetch event data from the database 
* @param array filter data based on the passed parameters 
*/ 
function getRows($params = array()){ 
$this->db->select('*'); 
$this->db->from($this->table); 
if(array_key_exists("where", $params)){ 
foreach($params['where'] as $key => $val){ 
$this->db->where($key, $val); 
} 
} 
if(array_key_exists("returnType",$params) && $params['returnType'] == 'count'){ 
$result = $this->db->count_all_results(); 
}else{ 
if(array_key_exists("id", $params) || (array_key_exists("returnType", $params) && $params['returnType'] == 'single')){ 
if(!empty($params['id'])){ 
$this->db->where('id', $params['id']); 
} 
$query = $this->db->get(); 
$result = $query->row_array(); 
}else{ 
$this->db->order_by('date', 'asc'); 
if(array_key_exists("start",$params) && array_key_exists("limit",$params)){ 
$this->db->limit($params['limit'],$params['start']); 
}elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){ 
$this->db->limit($params['limit']); 
} 

$query = $this->db->get(); 
$result = ($query->num_rows() > 0)?$query->result_array():FALSE; 
} 
} 
// Return fetched data 
return $result; 
} 
/* 
* Fetch and group by events based on date 
* @param array filter data based on the passed parameters 
*/ 
function getGroupCount($params = array()){ 
$this->db->select("date, COUNT(id) as event_num"); 
$this->db->from($this->table); 
if(array_key_exists("where", $params)){ 
foreach($params['where'] as $key => $val){ 
$this->db->where($key, $val); 
} 
} 
if(array_key_exists("where_year", $params)){ 
$this->db->where("YEAR(date) = ".$params['where_year']); 
} 
if(array_key_exists("where_month", $params)){ 
$this->db->where("MONTH(date) = ".$params['where_month']); 
} 
$this->db->group_by('date'); 
$query = $this->db->get(); 
$result = ($query->num_rows() > 0)?$query->result_array():FALSE; 
// Return fetched data 
return $result; 
} 
}

View the first calendar/

index.php (version 1.1)
The index() method of the Calendar controller is used to display the event calendar.

<!-- Display event calendar -->
<div id="calendar_div">
<?php echo $eventCalendar; ?>
</div>

Include the jQuery library in your code.

<!-- jQuery library -->
<script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>

Using jQuery and Ajax, the following code retrieves the calendar and events data.

The getCalendar() function makes an Ajax request to get calendar HTML from the Calendar controller’s eventCalendar() method.
The getEvents() function initiates an Ajax request to retrieve a list of events from the Calendar controller’s getEvents() method.

<script>
function getCalendar(target_div, year, month){
$.get( '<?php echo base_url('calendar/eventCalendar/'); ?>'+year+'/'+month, function( html ) {
$('#'+target_div).html(html);
});
}
function getEvents(date){
$.get( '<?php echo base_url('calendar/getEvents/'); ?>'+date, function( html ) {
$('#event_list').html(html);
});
}
</script>

By altering the year or month option, the following code can adjust the calendar days.

<script>
$(document).on("change", ".month-dropdown", function(){
getCalendar('calendar_div', $('.year-dropdown').val(), $('.month-dropdown').val());
});
$(document).on("change", ".year-dropdown", function(){
getCalendar('calendar_div', $('.year-dropdown').val(), $('.month-dropdown').val());
});
</script>

1.2. event-cal.php

is a PHP script that displays a calendar of upcoming events.
Create a huge calendar and fill it with events.

A year and month selection is offered in the header to travel to different months.
To move to the next or previous month, use the Next and Prev buttons.
The number of events is kept in each date cell. A tooltip showing the event number for the selected date shows when you hover over it.
The events are listed at the top of the calendar when you click the event number.

<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($calendar['date'].' - 1 Month')); ?>','<?php echo date("m",strtotime($calendar['date'].' - 1 Month')); ?>');"></a>
<div class="title-bar__month">
<select class="month-dropdown">
<?php echo $monthOptions; ?>
</select>
</div>
<div class="title-bar__year">
<select class="year-dropdown">
<?php echo $yearOptions; ?>
</select>
</div>
<a href="javascript:void(0);" class="title-bar__next" onclick="getCalendar('calendar_div','<?php echo date("Y",strtotime($calendar['date'].' + 1 Month')); ?>','<?php echo date("m",strtotime($calendar['date'].' + 1 Month')); ?>');"></a>
</section>
<aside class="calendar__sidebar" id="event_list">
<?php echo $eventList; ?>
</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<=$calendar['boxDisplay'];$cb++){ 
if(($cb >= $calendar['currentMonthFirstDay'] || $calendar['currentMonthFirstDay'] == 1) && $cb <= $calendar['totalDaysOfMonthDisplay']){ 
// Current date 
$dayCount = ($dayCount < 10 && strpos($dayCount, '0') == false)?'0'.$dayCount:$dayCount; 
$currentDate = $calendar['dateYear'].'-'.$calendar['dateMonth'].'-'.$dayCount; 
// Get number of events based on the current date 
$eventNum = 0; 
if(!empty($events)){ 
$eventData = array_filter($events, function ($var) use ($currentDate) { 
return ($var['date'] == $currentDate); 
}); 
$eventData = array_values($eventData); 
$eventData = !empty($eventData[0])?$eventData[0]:''; 
$eventNum = !empty($eventData['event_num'])?$eventData['event_num']:0; 
} 
// 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 < $calendar['currentMonthFirstDay']){ 
$inactiveCalendarDay = ((($calendar['totalDaysOfMonth_Prev']-$calendar['currentMonthFirstDay'])+1)+$cb); 
$inactiveLabel = 'expired'; 
}else{ 
$inactiveCalendarDay = ($cb-$calendar['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 != $calendar['boxDisplay'])?'</section><section class="calendar__week">':''; 
} 
echo '</section>'; 
?>
</section>
</main>

Note :

Our sample code demonstrates how to incorporate an event calendar into a CodeIgniter website. The events can be dynamically shown in the calendar from the database. Using jQuery and Ajax, this calendar allows users to navigate to other months without having to reload the website. You may easily customise the CodeIgniter event calendar to meet your specific requirements

PHPCODE © 2024