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.
- 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.');
}
}
});
});
- 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!
Written by Julien Charette
Related protips
8 Responses
Don't forget the 3 hidden fields you have to create in the html markup. What are those field
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'])) {
Thanks for pointing this out!
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.
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.
Where is json-events-feed.php file code? Please also provide that? Thanks.
I also have a question can i set a different data aside from title, start,end can i
I also have a question can i set a different data aside from title, start,end can i have different fields?