PHP Event Calendar is a user-friendly way to display events dynamically from the database. Not only list the events, but you can also provide an option to add events to the calendar for a specific date. Based on the selected date, the event will be added to the database and list on the calendar dynamically. In the previous PHP event calendar tutorial, you learned how to create an event calendar using jQuery, Ajax, and PHP. In this tutorial, we will enhance the functionality of the PHP event calendar script to show you how to add events to the calendar and display events from the MySQL database using jQuery and Ajax.
The following functionality will be implemented to build an event calendar and add events to calendar using PHP and MySQL.
Since this script is an enhancement of the PHP event calendar script, we will focus mainly on the add event functionality using jQuery, Ajax, PHP & MySQL. Before you begin, see the PHP event calendar tutorial first, it will help to understand our PHP event calendar script.
Before getting started, take a look at the file structure of the Add Event to PHP Calendar script.
php_event_calendar_add/ ├── index.php ├── functions.php ├── dbConfig.php ├── js/ │ ├── jquery.min.js │ └── sweetalert.min.js └── css/ └── style.css
A table is required to store the event information 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;
The MySQLi extension is used to connect 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 a calendar and add events with PHP and MySQL.
<?php
// Include the database config file
require_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;
case 'addEvent':
addEvent($_POST);
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">
<div id="event_list">
<?php echo getEvents(); ?>
</div>
<a href="javascript:void(0);" class="add-event-btn">+add event</a>
<div id="event_add_frm" style="display:none;">
<form id="eventAddFrm" action="#">
<div class="form-group">
<label>Event Title:</label>
<input type="text" class="form-control" name="event_title" id="event_title" required>
</div>
<div class="form-group">
<label>Date:</label>
<input type="text" class="form-control" name="event_date" id="event_date" value="<?php echo date("Y-m-d"); ?>" readonly>
</div>
<input type="submit" name="event_submit" class="btn btn-default" value="Submit">
</form>
</div>
</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);
}
});
// Add date to event form
$('#event_date').val(date);
}
function getCalendarEvents(target_div, year, month, date){
$.ajax({
type:'POST',
url:'functions.php',
data:'func=getCalender&year='+year+'&month='+month,
success:function(html){
$('#'+target_div).html(html);
getEvents(date);
}
});
}
$(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());
});
$('.add-event-btn').on('click',function(){
$('#event_add_frm').slideToggle();
});
$('#eventAddFrm').submit(function(event){
event.preventDefault();
$(':input[type="submit"]').prop('disabled', true);
$('#event_add_frm').css('opacity', '0.5');
$.ajax({
type:'POST',
url:'functions.php',
data:$('#eventAddFrm').serialize()+'&func=addEvent',
success:function(status){
if(status == 1){
//$('#eventAddFrm')[0].reset();
$('#event_title').val('');
swal("Success!", "Event added successfully.", "success");
}else{
swal("Failed!", "Something went wrong, please try again.", "error");
}
$(':input[type="submit"]').prop('disabled', false);
$('#event_add_frm').css('opacity', '');
var date = $('#event_date').val();
var dateSplit = date.split("-");
getCalendarEvents('calendar_div', dateSplit[0], dateSplit[1], date);
}
});
});
});
</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;
}
/*
* Insert events in the database
*/
function addEvent($postData){
$status = 0;
if(!empty($postData['event_title']) && !empty($postData['event_date'])){
global $db;
$event_title = $db->real_escape_string($postData['event_title']);
$insert = $db->query("INSERT INTO events (title, date) VALUES ('".$event_title."', '".$postData['event_date']."')");
if($insert){
$status = 1;
}
}
echo $status;
}
Call the getCalender() function to embed the event calendar with add option.
Event Calendar:
functions.php
).getCalender()
function to add calendar in the web page.Add Event to Calendar:
<?php
// Include calendar helper functions
require_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>
<!-- SweetAlert plugin to display alert -->
<script src="js/sweetalert.min.js"></script>
</head>
<body>
<!-- Display event calendar -->
<div id="calendar_div">
<?php echo getCalender(); ?>
</div>
</body>
</html>
This example PHP event calendar script helps you to embed a large calendar in the web page and list the events from the database. Also, you can allow the user to add events to the calendar without page refresh using jQuery, Ajax, PHP, and MySQL. The functionality of this event calendar can be enhanced to make it more user-friendly.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
good
Hi. First of all, congratulations for the excelent tutorial.
How do I how to start the week on Sunday?
How do I change date-format to dd/mm/YYYY format?
How do I change the language of calendar into Portuguese?
How do I implement edit/delete functions???
Thanks a lot.
Hi
How can i change the language for the calendar into French?
Best regards
Pierre
Thanks a lot
Hi
How can i change the language for the calendar (months) into Danish?
Best regards
Jan
How to change the first day of the week
Please I can’t find the css file for this ,where can i find it?. I need it urgently
Download the source code, it contains all the required files including CSS.
Thank you for this script.
How i can change date-format italian??
Thank you
I hope there will be an edit and delete function. Thank you!
I love the script
But, my current problem is adding a new field to the database inserting. I modify the code like i should but keep getting an error.
Hey Admin I want Same calender and functionality in codeigniter with bootstrap From whre I can Get Can You please help????
We will try to publish your requested tutorial soon. Meanwhile, subscribe our newsletter and follow us on social media to get notified.
How to delete an event..? can u please help me regarding this.
i want the events directly show inside date
how can i remove the events which are inserted by user
Hi sir. there is no delete event can you help me about that so i can add it. Thanks alot 😀
This was very great.
Is there a way to display the event titles in the date cells of the calendar? That would be very helpful
Thank you. You helped me a lot.
Thank you for the tutorial.
Please get me to delete the events from calendar.
Thank you so much for this
But give soon delete option.
Hello, thanks for a great script!
But how to start the week on monday?
how to delete an event
Hi,
This looks good but I have one query, here we are manually adding the event. Can we call the event from database and show it?
We’ve already published this tutorial, see from here – http://www.codexworld.com/build-event-calendar-using-jquery-ajax-php/
Hi,
You guys rock!
Can we have a date range added and also displayed in the calendar?
Very nice tutorial.
Did you plan to add a function which allow the selection of days or weeks and then create an event for the day/week selection ?
Thanks.