Fullcalendar with PHP and CodeIgniter - Database Events - Part 2

In this next tutorial, we are going to set up our database to store our Calendar events, then display them using FullCalendar and PHP. This tutorial is a continuation of our FullCalendar with PHP and CodeIgniter series. View previous parts:

  First, we need to create the datatable table that stores the events:

CREATE TABLE `calendar_events` (
 `ID` int(11) NOT NULL,
 `title` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
 `start` datetime NOT NULL,
 `end` datetime NOT NULL,
 `description` varchar(1000) COLLATE utf8_unicode_ci NOT NULL
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Now we need to modify our Calendar_model.php to include the methods to grab the events we need. We'll also add in the methods needed to create, edit and delete events.

Modify Calendar_model.php:

public function get_events($start, $end)
{
    return $this->db->where("start >=", $start)->where("end <=", $end)->get("calendar_events");
}

public function add_event($data)
{
    $this->db->insert("calendar_events", $data);
}

public function get_event($id)
{
    return $this->db->where("ID", $id)->get("calendar_events");
}

public function update_event($id, $data)
{
    $this->db->where("ID", $id)->update("calendar_events", $data);
}

public function delete_event($id)
{
    $this->db->where("ID", $id)->delete("calendar_events");
}

These are just some simple methods and they should be pretty self-explanatory. We'll be using the get_events() method for this part of the tutorial. The $start and $end values are going to be obtained from our FullCalendar plugin that generates them for us.

Since we haven't created adding events yet, let's add in some dummy data using SQL:

INSERT INTO `calendar_events` (`ID`, `title`, `start`, `end`, `description`) VALUES
(1, 'Test Event', '2017-03-16 00:00:00', '2017-03-16 00:00:00', ''),
(2, 'New Event', '2017-03-23 00:00:00', '2017-03-23 00:00:00', '');

Note: Change the dates above so that they correspond to your current month and year. This will allow you to see the events on the first page.

Next up, we need to modify our FullCalendar script to now include an Event Source that grabs events via AJAX.

Modify application/views/calendar/index.php:

 $('#calendar').fullCalendar({
     eventSources: [
         {
             events: function(start, end, timezone, callback) {
                 $.ajax({
                 url: '<?php echo base_url() ?>calendar/get_events',
                 dataType: 'json',
                 data: {
                 // our hypothetical feed requires UNIX timestamps
                 start: start.unix(),
                 end: end.unix()
                 },
                 success: function(msg) {
                     var events = msg.events;
                     callback(events);
                 }
                 });
             }
         },
     ]
 });

If you've ever used jQuery's AJAX method before, this code will look quite similar to you.

We send the start and end dates to our script calendar/get_events/. This allows us to grab the events between those dates (this stops us from grabbing all the events in the calendar at once - saving resources!). The unix() function generates a timestamp based on the current date.

The JavaScript variables start and end are generated by FullCalendar. FullCalendar will generate the dates based on the view of the calendar. We are using the default monthly view, so the start and end dates correspond to the beginning and end of the month.

Our controller function, get_events(), is yet to be created but notice that the dataType it returns is set to JSON. This is how FullCalendar handles it's event data so we need to send back JSON encoded data to FullCalendar.

The success: function() might look a little confusing but the callback(events) part is just our way of sending our event data back to FullCalendar to process the events we give it.

Let's create our get_events() function next so you can see how we get the calendar events data and process it.

Modify application/controllers/Calendar.php:

 public function get_events()
 {
     // Our Start and End Dates
     $start = $this->input->get("start");
     $end = $this->input->get("end");

     $startdt = new DateTime('now'); // setup a local datetime
     $startdt->setTimestamp($start); // Set the date based on timestamp
     $start_format = $startdt->format('Y-m-d H:i:s');

     $enddt = new DateTime('now'); // setup a local datetime
     $enddt->setTimestamp($end); // Set the date based on timestamp
     $end_format = $enddt->format('Y-m-d H:i:s');

     $events = $this->calendar_model->get_events($start_format, $end_format);

     $data_events = array();

     foreach($events->result() as $r) {

         $data_events[] = array(
             "id" => $r->ID,
             "title" => $r->title,
             "description" => $r->description,
             "end" => $r->end,
             "start" => $r->start
         );
     }

     echo json_encode(array("events" => $data_events));
     exit();
 }

The first thing we do is grab the $start and $end dates. We use PHP's Datetime function to convert the timestamps into the dates we need and setting the correct format. The format we are storing our events in is Y-m-d H:i:s. This is how PHP processes dates, you can read more about it here: http://php.net/manual/en/function.date.php

Now with all that new code added in, go back to your Calendar and you should now see the events being displayed to you. The events are coming directly from your database and so all that's left to do is implement adding, editing and deleting events directly from the Calendar.

We'll be doing that in the next tutorial!

Resources




Enjoyed that? Check These Posts Out

Learn Linux: Setup DNS Server with Bind On Debian

Using Datatables with CodeIgniter Tutorial

Fullcalendar with PHP and CodeIgniter - Database Events - Part 2

Top Alternatives to Photoshop and Creative Cloud Subscription

Article Comments

Let us know your thoughts below by adding a quick comment!

21/06/2017

Pallavi Koshti

it helps me lot thamkmyou

Reply

05/09/2017

Roman

No Events from DB showing. All i get is a GET Error on get_events. Any Idea?

Reply

10/09/2017

Patchesoft

@Roman do you have the exact error message you can send? Or a link?

Reply

11/09/2017

Najihah

it's really help me a lot but how to delete the word "12a" in the calendar..i don't want that words in my calendar display.

Reply

11/09/2017

Patchesoft

@Najihah Hi Najihah, 12a refers to the time of the event. Just add this option to your FullCalendar: displayEventTime: false

Reply

25/09/2017

Marvin Gifford

No events are displayed from DB, please help.

Reply

25/09/2017

Patchesoft

@Marvin Gifford Do you have a link I can view so I can see what might be causing the issue? Try using FireBug to inspect the response from the javascript request.

Reply

26/09/2017

otoy

@Patchesoft me too..no showing error response

Reply

26/09/2017

Marvin Gifford

@Patchesoft Hi, here's the link. Please and thank you.
https://tims.com.ph/calendar/index

Reply

26/09/2017

Patchesoft

@Marvin Gifford Thanks for that. If you check the result of your Calendar fetching the events here: https://tims.com.ph//calendar/get_events?start=1503792000&end=1507420800

It says this error:


A PHP Error was encountered

Severity: Notice

Message: Undefined property: stdClass::$ID

Filename: controllers/calendar.php

Line Number: 35


Have you made sure your ID in the Calendar_events table has an ID (uppercase letters) ? Because it's saying the row being returned from your database doesn't contain the ID element.

Reply

27/09/2017

Marvin Gifford

Hi Thank you very much for your response.

I was able to change to uppercase "id" to "ID" in Calendar_events table. However, still no events are displayed in full calendar.

http://tims.com.ph/calendar/get_events?start=1503792000&end=1507420800

{"events":[{"id":"1","title":"Sample","description":"Sample","end":"2017-09-26 11:34:00","start":"2017-09-26 11:34:00"}]}

Looking forward for your much needed help. Thank you!

Reply

27/09/2017

Marvin Gifford

My apologies for this one again. It doesn't seem to work in my localhost, but my codes are the same from the live site.
:(

Reply

27/09/2017

Patchesoft

@Marvin Gifford Localhost issues are harder to debug for me since I can't actually see the code. Normally the issue is down to the URL that is being called to grab the event data. Have you tried the tactic of seeing what FireBug says when you go to the event url?

url: 'calendar/get_events',

Reply

21/11/2017

pathi

hi

i could not have showing up full view of inserted event when click on event ..
click event just shows faded div without form to update..
i could not show and update additional fields ...

Reply

07/12/2017

Luis B

HI,

I had to set type: 'POST' within the AJAX call to get results in the array. If I don't set it I just get an empty array. Do you know why that happen?

Thanks,

Reply

25/12/2017

Muhammad Ihlasul Amal

Hei, can you help me. My view not appear that title calendar :(

Reply

23/01/2018

Neil Turton

Hi,

I am having a strange issue with getting it to pull from the database.

If you look here https://pushmb.co.uk/codeigniter/calendar/get_events?start=1514678400&end=1518307200

I am getting the following errors

Message: Undefined property: Calendar::$calendar_model

&

Message: Call to a member function get_events() on null

and I cannot for the life of me figure out why its coming up as null, I have even copied and pasted above tutorials in case I typed it in wrong.

Reply

24/01/2018

Patchesoft

@Neil Turton have you loaded the model? $this->load->model("calendar_model");

Reply

27/01/2018

John Paul

Thank you so much for this tutorial. You saved me! but why my event text color is black while yours is white? i've already tried color: 'yellow',
textColor: 'black'
but nothing happens

Reply

27/03/2018

Julians

Help me please
No events are displayed from DB, please help.

Reply

31/03/2018

Johannes Schmidt

I am woking on making a calendar for work. I saw your amazing good tutorial on how to get the fullcalendar to work with php using codeignite. I follow your tutorial, but do have a problem finding out were to put the create table you have as the first bit of code. Plese help.

Reply

03/05/2018

Cigale31

I managed to display the events, it is working now :
I modify in the file views/calendar/index.php :

Reply

28/05/2018

Arlan

Hello Thanks a lot for your tutorial, i get some problem here please help me, i set the date for 2 days like from 1 feb until 2 feb but its just show in 1 days, really need your help : ) thanks

Reply

07/07/2018

Bradon

Can't get events from the database

404 error The requested URL /projects/CodeIgniter/calendar/get_events was not found on this server

http://bradonckelley.me/projects/CodeIgniter/

Reply

06/08/2018

Anil

add index.php in your url after base path.otherwise add .htaccess file in your root folder.

Reply

16/08/2018

septi

@Cigale31 what changed from from index.php?? i code exactly same from this tutorial but the events just dont showing up...please tell what was changed..thank's

Reply

22/09/2018

juan

Dont you need this on your Calendar_model

public function __construct()
{
parent::__construct();
$this->load->database();
}

Reply

12/10/2018

Ahmad Wijaya

@Roman in my cases you should add index.php in the url. ex: url: 'index.php/calendar/get_events' that's fix my problem.

Reply

02/11/2018

syaiful

@Patchesoft Where I put the option?

Reply

02/11/2018

Amanda M

@Ahmad Wijaya Thank you! This is exactly what I needed.

Reply

03/11/2018

Adi Surahman

@Ahmad Wijaya this is help me too, thank you dude

Reply

Leave A Comment

X
- Amazon BLACK FRIDAY SALES ARE LIVE!
Click here to get discounts on gaming laptops, computers, monitors, software, games and so much more - ONLY this week!