Fetch and render events from MySQL to FullCalendar.js

Posted on

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!

Incoming search terms:

  • Fetch and render events from MySQL to FullCalendar js

Leave a Reply

Your email address will not be published.