tr64xg
Last Updated: February 25, 2016
·
53.22K
· 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

14236

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

over 1 year ago ·
16034

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 ·
16037

Thanks for pointing this out!

over 1 year ago ·
16040

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 ·
18967

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 ·
19323

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

over 1 year ago ·
20861

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

over 1 year ago ·
20862

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 ·