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.
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
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;
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);
}
The functions.php
file holds all the functions that are used to generate an event calendar with PHP and MySQL.
<?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;
}
Call the getCalender() function to display the event calendar on the web page.
functions.php
).getCalender()
function to add calendar in the web page.
<?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>
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.
PHP Event Calendar – Add/Edit/Delete Events
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.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Its the second time I am copying code from this website and I AM 100% SATISFIED. THANK U
Hi, and thanks for the script. How can I translate to spanish the calendar? Thanks in advance
i would like to have style.css
I was really helpfull..Thank you
where I can find the jquerymin.js and style.css files?
All the required files are included in the source code, download it.
Where ican download the needed jsquery library and the css file?
Download the source code ZIP, all the required files are included in it.
great work!!! thnk u. is there any way that i can change box color on weekend? i like to change saturday and sunday to pink color
how to disable the previous date?
How can I change the day of the week
can i have the css of add event
I would like to get modification code of getcalendar() method to make data cells clickable…
Send us your changes requirement to support@codexworld.com.
How can i make data cells clickable.?
You need to modify the
getCalender()
method infunctions.php
file. If you want help on modification, email us at support@codexworld.com.hlo brother where is css source code..please give me the link ..
The source code contains all the required files including CSS, please download it from the above link.
I read your tutorial and I only have one problem the css is not in the tutorial and I need this
The source code contains the CSS, download the source code.
Great work..Keep it up…You r saving my time a lot…Thank You so much
great piece of work you have here. In reviewing your tutorial and code I have as of yet been unable to add events to the db…
my db has the following `Name`, `StartonDate`,` CutoffDate` rather than date and status as in your config file.
As @Anjana said, if we can show the events in the calendar rather than a popup and from the startondate through the cutoffdate then I can use those to link to other things.
If there is a cost to this I would consider it
Please send your modification requirement details at admin@codexworld.com. We’ll get back to you soon.
i want to evetns in place of view event…
HOW CAN I INSERT EVENT IN DATABASE ….
How I can change the color of particular day in a week
This is a great tutorial, but is there a way that I can view the events on the inside of the calendar? Like in real-life calendars, I’d like to put the events below its dates.
Somehow like this.. the events are inside the date cell/box.
___________
| 1. |
| Event 1 |
| Event 2 |
how we can drag the even from one date to another.please help
for monday at start add this in getCalendar
function getCalender($year = ”,$month = ”)
{
$dateYear = ($year != ”)?$year:date(“Y”);
$dateMonth = ($month != ”)?$month:date(“m”);
$date = $dateYear.’-‘.$dateMonth.’-01′;
$currentMonthFirstDay = date(“N”,strtotime($date));
if ($currentMonthFirstDay == 7)
$currentMonthFirstDay = 6;
elseif ($currentMonthFirstDay == 6)
$currentMonthFirstDay = 5;
elseif ($currentMonthFirstDay == 5)
$currentMonthFirstDay = 4;
elseif ($currentMonthFirstDay == 4)
$currentMonthFirstDay = 3;
elseif ($currentMonthFirstDay == 3)
$currentMonthFirstDay = 2;
elseif ($currentMonthFirstDay == 2)
$currentMonthFirstDay = 1;
elseif ($currentMonthFirstDay == 1)
$currentMonthFirstDay = 7;
@codexworld I’m from Germany and I want to change the code so monday is standing at the very left and sunday at the very right. I tried my best but it didn’t work. Could you please help me?
add event feature pls
We’ve already published Add Event to Calendar tutorial, checkout it from here – http://www.codexworld.com/add-event-to-calendar-using-jquery-ajax-php/
thank you! you save my project in viewing of schedule using events calendar in php.
This is a great tutorial, but is there a way that I can view the events on the inside of the calendar? Like in real-life calendars, I’d like to put the events below its dates.
Somehow like this.. the events are inside the date cell/box.
___________
| 1. |
| Event 1 |
| Event 2 |
|__________|
Hi. if i would like to update and delete a current event in the database already , how do i do so ?
Thanks in Advance !
Thank you for this tutorial.
Please tell me how to start week from monday 🙂
how to add events in calendar
@Manu Read the tutorial on how to add Event to Calendar using jQuery, Ajax, PHP and MySQL from here – http://www.codexworld.com/add-event-to-calendar-using-jquery-ajax-php/
Hello!
First of all: Thank you so much for this awesome code.
I need some help tho… I am very new to jquery and all, and I would like to change the names of the months and the week-days to swedish. Is this possible to do this, and how to do it in that case?
Thank you in advance.
I want to connect my calendar to event page as well, will this calendar work?
How to add new events
@Hasif We’ve published PHP Event Calendar Part 2 where the script have extended with add event functionality. Read add Event to Calendar using jQuery, Ajax, PHP and MySQL from here – http://www.codexworld.com/add-event-to-calendar-using-jquery-ajax-php/
Yes, the problem is fixed now. Thank you very much. Another thing I wanted to ask, the current version is showing the date in yyyy-mm-d format whereas I want in dd-mm-yyyy. How can I fix that. Thanks.
Hi,
I downloaded the calendar and it is working. There’s a slight issue though, basically when the event is added on the database it comes on the calendar (displays sky blue colour) with next and previous link only, not with the drop down. I would be very grateful if you can help me with this.
Thanks
@Abdullah Thanks for notifying us about this issue. We’ve fixed this issue and updated the source code. Please use the updated version.
how to add new events
Hie Developer. Thank you for the code. I am kindly asking for the other code of how to add events in the database
how can i download the file…
@Yong You can download the source file from here – http://www.codexworld.com/downloads/build-event-calendar-using-jquery-ajax-php
@codexworld can you please say how to add event?
demo not working sir..
@Zul Thanks for notifying us about this issue. We’ve resolved this issue, now you can check the demo.
what if i what to add an update button beside the description of the event so the status in the database will update?
@Joyce We’ll publish the part 2 of this tutorial soon. Your required feature will be implemented into part 2.
How to add new events
@Varad Our next tutorial will show you the add events feature and it will come soon. Please subscribe our newsletter for getting the tutorial in your mailbox.