X

How to integrate jQuery FullCalendar with PHP & MySQL Example

Users will find it easy to manage events in a calendar. For form-based event management, users will need to provide more information such as event title, date range, and other details. In calendar view management, however, the user can only give the title and select the date. This will allow the user to manage his daily events quickly.

If you are looking for a Web tutorial on how to utilize the FullCalendar.js plugin on a PHP dynamic website for scheduling our event or meeting at the date and time of our choice. In this article, we’ve discussed how to integrate Jquery FullCalendar Plugin to work with PHP server-side scripts in conjunction with the Mysql database tables. If you’re running a site for managing events, such as organizing meetings or planning the execution of any task on a certain date, the information can be seen on the website with a calendar. To accomplish these tasks you could use the Fullcalender plugin to make a more effective alternative to other.

FullCalendar.js plug-in is a Javascript calendar that uses any web-based technology and is simple to integrate with any server-side script, such as PHP. With this plugin, it is possible to play with databases such as Mysql and MySQL. It’s a Jquery library that displays an online calendar page, with the events we’ve scheduled on specific dates and times. It not only displays information about the calendar for the month, but it displays other details of the calendar such as weekdays and specific times of day details as well. The plugin is extremely simple to use, for instance, it is possible to activate this plugin on a certain webpage, we’ve created the fullCalendar() method which will be activated only on a specific page.

To talk about ways to integrate this plugin to PHP and Mysql databases, here is an easy CRUD(Create Read, Update, Create delete) operation using PHP Script and Mysql Data. In the beginning, we need to download information from databases, then show data on the calendar to do this, we’ve employed the event method. This method will be referred to as the PHP page. When it is accessed via an internet server, it will transmit information in JSON string format. The data will appear as a calendar. A similar method for adding events, we must utilize the select method in this plugin. With this method, we can select a specific date cell, and then create a new event for the date. After we have added a new event, then we need to alter the dates or times of an event. For this, we must make use of the eventDrop and eventResize methods. This method can alter the date and timing of a particular event. In addition, we would like to delete a particular event. For this, we’ve used the eventClick method. Using this method, when you click on an event, it triggers an ajax call to delete information about the event out of the MySQL table. In this way, we are able to perform Insert, Update deletion, Select and Insert operations using this plugin making use of PHP scripts with Mysql. Below, we have provided the source code as well.

I used FullCalendar JavaScript to add and manage events with a PHP calendar. It is open-source and easy to integrate it into your application.

See Also: Simple PHP REST API with Slim, PHP & MySQL

This library supports event CRUD functionality. I used jQuery AJAX to call PHP to handle event CRUD operation with the database. FullCalendar allows you to drag and drop events from one date to the next.

It supports event resizing, which allows you to increase or decrease the event duration.

This is the output of the PHP event management example using FullCalendar library.

full calendar PHP MySQL example

You can add, edit and delete events.

Step 1. Download FullCalendar plugin from here.

Step 2. Create database table events

CREATE TABLE events (



  id int(11) NOT NULL AUTO_INCREMENT,



  start datetime DEFAULT NULL,



  end datetime DEFAULT NULL,



  title text,



  uid varchar(100),



  PRIMARY KEY (id)



) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Step 3. Code includes below jQuery and CSS scripts

<!— jQuery —>



<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>



 

<!— custom scripts —> 



<script type="text/javascript" src="js/script.js"></script> 





<!— bootstrap —>



<script src="bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script>



<link  href="bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" >

 

<!— fullcalendar —>



<link href="css/fullcalendar.css" rel="stylesheet" />



<link href="css/fullcalendar.print.css" rel="stylesheet" media="print" />



<script src="js/moment.min.js"></script>



<script src="js/fullcalendar.js"></script>

PHP Files and coding:

database.php

<?php



    $con = mysqli_connect('localhost','DataBaseUser','DataBasePassword','DataBaseName') or die(mysqli_error($con));



?>

Edit this file and add your database credentials.

index.php

The index file contains all the actions add an event, edit an event, delete events, and load events.

You can separate all actions into different files such as addevent.php, editevent.php, deleteevent.php, and loadevents.php, etc.

<?php



include("database.php");



    



if(isset($_POST['action']) or isset($_GET['view'])) //show all events



{



    if(isset($_GET['view']))



    {



        header('Content-Type: application/json');



        $start = mysqli_real_escape_string($connection,$_GET["start"]);



        $end = mysqli_real_escape_string($connection,$_GET["end"]);



        



        $result = mysqli_query($connection,"SELECT id, start ,end ,title FROM  events where (date(start) >= ‘$start’ AND date(start) <= ‘$end’)");



        while($row = mysqli_fetch_assoc($result))



        {



            $events[] = $row; 



        }



        echo json_encode($events); 



        exit;



    }



    elseif($_POST['action'] == "add") // add new event section



    {   



        mysqli_query($connection,"INSERT INTO events (



                    title ,



                    start ,



                    end 



                    )



                    VALUES (



                    '".mysqli_real_escape_string($connection,$_POST["title"])."',



                    '".mysqli_real_escape_string($connection,date('Y-m-d H:i:s',strtotime($_POST["start"])))."‘,



                    '".mysqli_real_escape_string($connection,date('Y-m-d H:i:s',strtotime($_POST["end"])))."‘



                    )");



        header('Content-Type: application/json');



        echo '{"id":"'.mysqli_insert_id($connection).'"}';



        exit;



    }



    elseif($_POST['action'] == "update")  // update event



    {



        mysqli_query($connection,"UPDATE events set 



            start = '".mysqli_real_escape_string($connection,date('Y-m-d H:i:s',strtotime($_POST["start"])))."', 



            end = '".mysqli_real_escape_string($connection,date('Y-m-d H:i:s',strtotime($_POST["end"])))."' 



            where id = '".mysqli_real_escape_string($connection,$_POST["id"])."'");



        exit;



    }



    elseif($_POST['action'] == "delete")  // remove event



    {



        mysqli_query($connection,"DELETE from events where id = '".mysqli_real_escape_string($connection,$_POST["id"])."'");



        if (mysqli_affected_rows($connection) > 0) {



            echo "1";



        }



        exit;



    }



}



?>

script.js

This file contains all the actions and sends a request to a server and receives a response.

$(document).ready(function(){

        var calendar = $('#calendar').fullCalendar({

            header:{

                left: 'prev,next today',

                center: 'title',

                right: 'agendaWeek,agendaDay'

            },

            defaultView: 'agendaWeek',

            editable: true,

            selectable: true,

            allDaySlot: false,

            

            events: "index.php?view=1",

   

            

            eventClick:  function(event, jsEvent, view) {

                endtime = $.fullCalendar.moment(event.end).format('h:mm');

                starttime = $.fullCalendar.moment(event.start).format('dddd, MMMM Do YYYY, h:mm');

                var mywhen = starttime + ' - ' + endtime;

                $('#modalTitle').html(event.title);

                $('#modalWhen').text(mywhen);

                $('#eventID').val(event.id);

                $('#calendarModal').modal();

            },

            

            //header and other values

            select: function(start, end, jsEvent) {

                endtime = $.fullCalendar.moment(end).format('h:mm');

                starttime = $.fullCalendar.moment(start).format('dddd, MMMM Do YYYY, h:mm');

                var mywhen = starttime + ' - ' + endtime;

                start = moment(start).format();

                end = moment(end).format();

                $('#createEventModal #startTime').val(start);

                $('#createEventModal #endTime').val(end);

                $('#createEventModal #when').text(mywhen);

                $('#createEventModal').modal('toggle');

           },

           eventDrop: function(event, delta){

               $.ajax({

                   url: 'index.php',

                   data: 'action=update&title='+event.title+'&start='+moment(event.start).format()+'&end='+moment(event.end).format()+'&id='+event.id ,

                   type: "POST",

                   success: function(json) {

                   //alert(json);

                   }

               });

           },

           eventResize: function(event) {

               $.ajax({

                   url: 'index.php',

                   data: 'action=update&title='+event.title+'&start='+moment(event.start).format()+'&end='+moment(event.end).format()+'&id='+event.id,

                   type: "POST",

                   success: function(json) {

                       //alert(json);

                   }

               });

           }

        });

               

       $('#submitButton').on('click', function(e){

           // We don't want this to act as a link so cancel the link action

           e.preventDefault();

           doSubmit();

       });

       

       $('#deleteButton').on('click', function(e){

           // We don't want this to act as a link so cancel the link action

           e.preventDefault();

           doDelete();

       });

       

       function doDelete(){

           $("#calendarModal").modal('hide');

           var eventID = $('#eventID').val();

           $.ajax({

               url: 'index.php',

               data: 'action=delete&id='+eventID,

               type: "POST",

               success: function(json) {

                   if(json == 1)

                        $("#calendar").fullCalendar('removeEvents',eventID);

                   else

                        return false;

                    

                   

               }

           });

       }

       function doSubmit(){

           $("#createEventModal").modal('hide');

           var title = $('#title').val();

           var startTime = $('#startTime').val();

           var endTime = $('#endTime').val();

           

           $.ajax({

               url: 'index.php',

               data: 'action=add&title='+title+'&start='+startTime+'&end='+endTime,

               type: "POST",

               success: function(json) {

                   $("#calendar").fullCalendar('renderEvent',

                   {

                       id: json.id,

                       title: title,

                       start: startTime,

                       end: endTime,

                   },

                   true);

               }

           });

           

       }

    });

That’s all for a unique and straightforward events application. I hope you all like this script, please feel free to comment your issues below.

Please comment below if you face any issues.

Huzoor Bux: I am a PHP Developer

View Comments (15)

  • Hi, thanks for this codes. I am able to add the events to database, but when i refresh the page the event gone. What could be the problem? Thanks.

  • I only have Week & Day view. How can i enable Month view? Thanks thought for the tutorial!. ')

  • when i'm try to add months on header it does not look on main page and also not able to run minTime and maxTime

  • I can add event but when refresh its gone

    PHP Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in index.php on line 20

    this is the code in line 20
    while($row = mysqli_fetch_assoc($result))

  • great code .
    how can i get add external-events drag and drop and how to add description when i add a event .

  • Hi, thanks for this codes. I am able to add the events to database, but when i refresh the page the event gone. What could be the problem? Thanks.

  • I notice that in fullcalendar.js there is working hours, how can i set that?

    Can i change the timeformat to 24 hour format also in the left collum where it says am and pm ?