Last Updated: February 25, 2016
·
61.88K
· juliencharette

Fetch and render events from MySQL to FullCalendar.js

This small tutorial will teach you the basics of fetching events from MySQL and render the data with FullCalendar.js using PHP, Javascript and PDO. Let's do it in 2 easy steps.

  1. Create an html file which will output the final result:

calendar.html

<div id="calendar"></div>

$(document).ready(function() {
    var calendar = $('#calendar').fullCalendar({
        defaultView: 'agendaWeek',
        events: {
            url: 'json-events-feed.php',
            type: 'POST', // Send post data
            error: function() {
                alert('There was an error while fetching events.');
            }
        }
    });
});

  1. Create a php file which will echo our events in json format:

events.php

try {

    // Connect to database
    $connection = new PDO($url, $username, $password);

    // Prepare and execute query
    $query = "SELECT * FROM events";
    $sth = $connection->prepare($query);
    $sth->execute();

    // Returning array
    $events = array();

    // Fetch results
    while ($row = $sth->fetch(PDO::FETCH_ASSOC) {

        $e = array();
        $e['id'] = $row['id'];
        $e['title'] = "Lorem Ipsum";
        $e['start'] = $row['start'];
        $e['end'] = $row['end'];
        $e['allDay'] = false;

        // Merge the event array into the return array
        array_push($events, $e);

    }

    // Output json for our calendar
    echo json_encode($events);
    exit();

} catch (PDOException $e){
    echo $e->getMessage();
}

Of course, there's room for optimization and further customization. Check out the API for the full feature list.

Have fun!

8 Responses
Add your response

Don't forget the 3 hidden fields you have to create in the html markup. What are those field

over 1 year ago ·

Hi,
Thank you for this tutorial, but there is an error in your code, you are missing a ' inside json-events-feed.php in the second line after "hiddenAllDay" :

if(!isset($POST['hiddenStart'], $POST['hiddenEnd'], $_POST['hiddenAllDay'])) {

over 1 year ago ·

Thanks for pointing this out!

over 1 year ago ·

I was actually using this bit of code in a project where I would use the data of a selected date. I will edit this protip and remove the "hidden fields" portion.

over 1 year ago ·

Thanks for the code, but I'm having trouble implementing it in my website. I keeps returning the error message that it had an error fetching the events.

over 1 year ago ·

Where is json-events-feed.php file code? Please also provide that? Thanks.

over 1 year ago ·

I also have a question can i set a different data aside from title, start,end can i

over 1 year ago ·

I also have a question can i set a different data aside from title, start,end can i have different fields?

over 1 year ago ·