Implementing Bootstrap Calendar in PHP and MySQLi

Today, we will implement a calendar application using Bootstrap Calendar for the front-end interface. The application will utilize MySQLi prepared statements to securely store events in a MySQL database. Users will have the ability to create, edit, and delete events seamlessly. So, let’s have a look at the code.

<?php
// Database connection
$host = 'localhost';
$user = 'root';
$password = '';
$dbname = 'calendar_db';

$conn = new mysqli($host, $user, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Create event
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_event'])) {
    $title = $_POST['title'];
    $start = $_POST['start'];
    $end = $_POST['end'];

    $stmt = $conn->prepare("INSERT INTO events (title, start, end) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $title, $start, $end);
    $stmt->execute();
    $stmt->close();
}

// Edit event
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_event'])) {
    $id = $_POST['id'];
    $title = $_POST['title'];
    $start = $_POST['start'];
    $end = $_POST['end'];

    $stmt = $conn->prepare("UPDATE events SET title=?, start=?, end=? WHERE id=?");
    $stmt->bind_param("sssi", $title, $start, $end, $id);
    $stmt->execute();
    $stmt->close();
}

// Delete event
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_event'])) {
    $id = $_POST['id'];

    $stmt = $conn->prepare("DELETE FROM events WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->close();
}

// Fetch events
$result = $conn->query("SELECT * FROM events");
$events = [];
while ($row = $result->fetch_assoc()) {
    $events[] = $row;
}
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <title>Calendar</title>
</head>
<body>
    <div class="container">
        <h2>Event Calendar</h2>
        <div id="calendar"></div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#calendar').fullCalendar({
                events: <?php echo json_encode($events); ?>,
                editable: true,
                eventLimit: true,
                selectable: true,
                select: function(start, end) {
                    var title = prompt('Event Title:');
                    if (title) {
                        $.ajax({
                            url: 'your_php_file.php',
                            type: 'POST',
                            data: {
                                create_event: true,
                                title: title,
                                start: start.format(),
                                end: end.format()
                            },
                            success: function() {
                                $('#calendar').fullCalendar('refetchEvents');
                            }
                        });
                    }
                    $('#calendar').fullCalendar('unselect');
                },
                eventClick: function(event) {
                    var title = prompt('Edit Event Title:', event.title);
                    if (title) {
                        $.ajax({
                            url: 'your_php_file.php',
                            type: 'POST',
                            data: {
                                edit_event: true,
                                id: event.id,
                                title: title,
                                start: event.start.format(),
                                end: event.end.format()
                            },
                            success: function() {
                                $('#calendar').fullCalendar('refetchEvents');
                            }
                        });
                    }
                },
                eventRender: function(event, element) {
                    element.append("<span class='closeon'>×</span>");
                    element.find(".closeon").click(function() {
                        if (confirm("Are you sure you want to delete this event?")) {
                            $.ajax({
                                url: 'your_php_file.php',
                                type: 'POST',
                                data: {
                                    delete_event: true,
                                    id: event.id
                                },
                                success: function() {
                                    $('#calendar').fullCalendar('refetchEvents');
                                }
                            });
                        }
                    });
                }
            });
        });
    </script>
</body>
</html>

The provided code implements a simple calendar application using PHP, MySQLi, and Bootstrap Calendar. Here’s a breakdown of the key components:

  1. Database Connection: The code establishes a connection to a MySQL database using MySQLi. It checks for connection errors and terminates if any are found.
  2. Event Management:
    • Create Event: When a POST request is made with the create_event parameter, the code retrieves the event title, start, and end times from the form data. It then prepares and executes an SQL statement to insert the new event into the database.
    • Edit Event: Similar to creating an event, if the edit_event parameter is present, the code updates the existing event in the database using the provided ID.
    • Delete Event: When a POST request with the delete_event parameter is received, the code deletes the specified event from the database.
  3. Fetching Events: The code retrieves all events from the database and stores them in an array, which is then encoded as JSON for use in the JavaScript calendar.
  4. Front-End Implementation: The HTML structure includes Bootstrap and FullCalendar libraries. The calendar is initialized with the fetched events, and users can create, edit, and delete events through user interactions.
  5. JavaScript Functionality: The JavaScript code handles user interactions with the calendar, such as selecting a date to create an event, clicking on an event to edit it, and rendering a delete button for each event.

This implementation provides a robust foundation for a calendar application, allowing for easy management of events while ensuring secure database interactions through prepared statements.

Happy Coding. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *