How to develop Projects(EMS) Using PHP and Mysql Part 9

Rashmi Mishra
0


How to develop Projects(EMS) Using PHP and Mysql   
Part 9

📌 Folder Structure:

/event-management/

│── /events/                

│   ├── add_event.php          # Add a new event 

│   ├── edit_event.php         # Edit an existing event 

│   ├── delete_event.php       # Delete an event 

│   ├── event_list.php         # List all events 

│   ├── view_event.php         # Display single event details 

│── uploads/             # Stores uploaded images

📌 Required Database Table (events)

Make sure you have this table in your database:

CREATE TABLE events (

    id INT AUTO_INCREMENT PRIMARY KEY,

    title VARCHAR(255) NOT NULL,

    description TEXT,

    event_date DATETIME NOT NULL,

    location VARCHAR(255) NOT NULL,

    organizer_id INT,

    image VARCHAR(255),

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    FOREIGN KEY (organizer_id) REFERENCES users(id) ON DELETE SET NULL

);


📌 File: events/add_event.php

<?php

// Include database connection

include('../config/db.php');

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Get form input data

    $title = mysqli_real_escape_string($conn, $_POST['title']);

    $description = mysqli_real_escape_string($conn, $_POST['description']);

    $event_date = mysqli_real_escape_string($conn, $_POST['event_date']);

    $location = mysqli_real_escape_string($conn, $_POST['location']);

    $organizer_id = 1; // Hardcoded for now, change based on logged-in user

    // Handle file upload

    $image = '';

    if (!empty($_FILES['image']['name'])) {

        $target_dir = "../uploads/";

        $image = basename($_FILES["image"]["name"]);

        $target_file = $target_dir . $image;

        move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);

    }

    // Insert query using MySQLi

    $sql = "INSERT INTO events (title, description, event_date, location, organizer_id, image)

            VALUES ('$title', '$description', '$event_date', '$location', '$organizer_id', '$image')";

    if (mysqli_query($conn, $sql)) {

        echo "<script>alert('Event added successfully!'); window.location='event_list.php';</script>";

    } else {

        echo "Error: " . mysqli_error($conn);

    }

 

    // Close connection

    mysqli_close($conn);

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Add Event</title>

    <link rel="stylesheet" href="../assets/style.css">

</head>

<body>

    <h2>Add New Event</h2>

    <form action="" method="POST" enctype="multipart/form-data">

        <label>Title:</label>

        <input type="text" name="title" required>

        <label>Description:</label>

        <textarea name="description" required></textarea>

        <label>Event Date:</label>

        <input type="datetime-local" name="event_date" required>

        <label>Location:</label>

        <input type="text" name="location" required>

        <label>Upload Image:</label>

        <input type="file" name="image">

        <button type="submit">Add Event</button>

    </form>

</body>

</html>


📌 Explanation of the Code:

✅ Uses MySQLi Procedural Queries
✅ Database Connection: Includes db.php for MySQLi connection
✅ User Input Handling: Uses mysqli_real_escape_string() to prevent SQL injection
✅ File Uploading: Saves event image in uploads/ folder
✅ Success Message: Displays alert on successful insertion
✅ Redirects to event_list.php after adding



📌 File: events/edit_event.php

<?php

// Include database connection

include('../config/db.php');

// Get event ID from URL

if (isset($_GET['id'])) {

    $event_id = $_GET['id'];

    // Fetch event details

    $query = "SELECT * FROM events WHERE id = $event_id";

    $result = mysqli_query($conn, $query);

    if (mysqli_num_rows($result) > 0) {

        $event = mysqli_fetch_assoc($result);

    } else {

        echo "<script>alert('Event not found!'); window.location='event_list.php';</script>";

        exit;

    }

}

 

// Handle form submission

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $title = mysqli_real_escape_string($conn, $_POST['title']);

    $description = mysqli_real_escape_string($conn, $_POST['description']);

    $event_date = mysqli_real_escape_string($conn, $_POST['event_date']);

    $location = mysqli_real_escape_string($conn, $_POST['location']);

    $organizer_id = 1; // Hardcoded, replace with logged-in user ID

 

    // Handle file upload

    $image = $event['image']; // Default to existing image

    if (!empty($_FILES['image']['name'])) {

        $target_dir = "../uploads/";

        $image = basename($_FILES["image"]["name"]);

        $target_file = $target_dir . $image;

        move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);

    }

 

    // Update event details

    $sql = "UPDATE events

            SET title = '$title', description = '$description', event_date = '$event_date',

                location = '$location', organizer_id = '$organizer_id', image = '$image'

            WHERE id = $event_id";

 

    if (mysqli_query($conn, $sql)) {

        echo "<script>alert('Event updated successfully!'); window.location='event_list.php';</script>";

    } else {

        echo "Error updating event: " . mysqli_error($conn);

    }

}

 

// Close connection

mysqli_close($conn);

?>

 

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Edit Event</title>

    <link rel="stylesheet" href="../assets/style.css">

</head>

<body>

    <h2>Edit Event</h2>

    <form action="" method="POST" enctype="multipart/form-data">

        <label>Title:</label>

        <input type="text" name="title" value="<?php echo $event['title']; ?>" required>

 

        <label>Description:</label>

        <textarea name="description" required><?php echo $event['description']; ?></textarea>

 

        <label>Event Date:</label>

        <input type="datetime-local" name="event_date" value="<?php echo date('Y-m-d\TH:i', strtotime($event['event_date'])); ?>" required>

 

        <label>Location:</label>

        <input type="text" name="location" value="<?php echo $event['location']; ?>" required>

 

        <label>Current Image:</label>

        <?php if ($event['image']) : ?>

            <img src="../uploads/<?php echo $event['image']; ?>" width="100"><br>

        <?php endif; ?>

       

        <label>Upload New Image (optional):</label>

        <input type="file" name="image">

 

        <button type="submit">Update Event</button>

    </form>

</body>

</html>


📌 Explanation of the Code:

✅ Uses MySQLi Procedural Queries
✅ Fetches Event Data Based on id in URL
✅ Displays Current Event Data in Input Fields
✅ Handles Image Uploading (Keeps Existing Image if No New Upload)
✅ Updates Event Details in Database
✅ Redirects to event_list.php After Successful Update


📌 File: events/delete_event.php

<?php

// Include database connection

include('../config/db.php');

// Check if the event ID is set

if (isset($_GET['id'])) {

    $event_id = $_GET['id'];

    // Fetch the event details to get the image file name

    $query = "SELECT image FROM events WHERE id = $event_id";

    $result = mysqli_query($conn, $query);

    if (mysqli_num_rows($result) > 0) {

        $event = mysqli_fetch_assoc($result);

       

        // Delete event image if exists

        if (!empty($event['image'])) {

            $image_path = "../uploads/" . $event['image'];

            if (file_exists($image_path)) {

                unlink($image_path); // Remove image from folder

            }

        }

 

        // Delete event from database

        $delete_query = "DELETE FROM events WHERE id = $event_id";

        if (mysqli_query($conn, $delete_query)) {

            echo "<script>alert('Event deleted successfully!'); window.location='event_list.php';</script>";

        } else {

            echo "Error deleting event: " . mysqli_error($conn);

        }

    } else {

        echo "<script>alert('Event not found!'); window.location='event_list.php';</script>";

    }

} else {

    echo "<script>alert('Invalid request!'); window.location='event_list.php';</script>";

}

 

// Close connection

mysqli_close($conn);

?>


📌 Explanation of the Code:

✅ Checks if the id parameter is provided in the URL.
✅ Fetches event details before deletion (to remove the associated image).
✅ Deletes the event's image file from the /uploads/ folder (if exists).
✅ Deletes the event record from the database.
✅ Redirects back to event_list.php after successful deletion.


📌 How to Use

1.   Navigate to event_list.php where events are listed.

2.   Add a delete button linking to delete_event.php?id=EVENT_ID.

3.   Clicking the delete button will trigger the deletion of the event and its image.


📌 File: events/event_list.php

<?php

// Include database connection

include('../config/db.php');

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Event List</title>

    <link rel="stylesheet" href="../assets/style.css">

    <style>

        table {

            width: 100%;

            border-collapse: collapse;

            margin-top: 20px;

        }

        table, th, td {

            border: 1px solid black;

            padding: 10px;

            text-align: left;

        }

        th {

            background-color: #f4f4f4;

        }

        .action-buttons a {

            text-decoration: none;

            padding: 5px 10px;

            margin-right: 5px;

            border-radius: 5px;

            color: white;

        }

        .edit-btn {

            background-color: #28a745;

        }

        .delete-btn {

            background-color: #dc3545;

        }

    </style>

</head>

<body>

 

    <h2>Event List</h2>

 

    <a href="add_event.php">➕ Add New Event</a>

 

    <table>

        <thead>

            <tr>

                <th>ID</th>

                <th>Title</th>

                <th>Description</th>

                <th>Event Date</th>

                <th>Location</th>

                <th>Image</th>

                <th>Actions</th>

            </tr>

        </thead>

        <tbody>

 

            <?php

            // Fetch all events from the database

            $query = "SELECT * FROM events ORDER BY event_date DESC";

            $result = mysqli_query($conn, $query);

 

            if (mysqli_num_rows($result) > 0) {

                while ($row = mysqli_fetch_assoc($result)) {

                    echo "<tr>

                        <td>{$row['id']}</td>

                        <td>{$row['title']}</td>

                        <td>{$row['description']}</td>

                        <td>{$row['event_date']}</td>

                        <td>{$row['location']}</td>

                        <td>";

                    if (!empty($row['image'])) {

                        echo "<img src='../uploads/{$row['image']}' width='80' height='50'>";

                    } else {

                        echo "No Image";

                    }

                    echo "</td>

                        <td class='action-buttons'>

                            <a href='edit_event.php?id={$row['id']}' class='edit-btn'>✏️ Edit</a>

                            <a href='delete_event.php?id={$row['id']}' class='delete-btn' onclick='return confirm(\"Are you sure you want to delete this event?\");'>❌ Delete</a>

                        </td>

                    </tr>";

                }

            } else {

                echo "<tr><td colspan='7'>No events found.</td></tr>";

            }

 

            // Close database connection

            mysqli_close($conn);

            ?>

 

        </tbody>

    </table>

 

</body>

</html>


📌 Explanation of the Code:

✅ Fetches all event records from the database.
✅ Displays event details including title, description, date, location, and image.
✅ Provides "Edit" and "Delete" buttons for each event.
✅ Uses confirm() JavaScript function to confirm before deletion.
✅ "Add New Event" button redirects to add_event.php.


📌 How to Use

1.   Ensure the database and events table exist.

2.   Add new events using add_event.php.

3.   Navigate to event_list.php to view all events.

4.   Edit or delete events using respective buttons.



📌 File: events/view_event.php

<?php

// Include database connection

include('../config/db.php');

// Check if the event ID is provided in the URL

if (isset($_GET['id']) && is_numeric($_GET['id'])) {

    $event_id = $_GET['id'];

    // Fetch event details from the database

    $query = "SELECT * FROM events WHERE id = ?";

    $stmt = mysqli_prepare($conn, $query);

    mysqli_stmt_bind_param($stmt, "i", $event_id);

    mysqli_stmt_execute($stmt);

    $result = mysqli_stmt_get_result($stmt);

 

    // Check if event exists

    if ($row = mysqli_fetch_assoc($result)) {

        $title = $row['title'];

        $description = $row['description'];

        $event_date = $row['event_date'];

        $location = $row['location'];

        $image = $row['image'];

    } else {

        echo "<p>Event not found.</p>";

        exit;

    }

} else {

    echo "<p>Invalid request.</p>";

    exit;

}

?>

 

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>View Event</title>

    <link rel="stylesheet" href="../assets/style.css">

    <style>

        .event-container {

            max-width: 600px;

            margin: 50px auto;

            padding: 20px;

            border: 1px solid #ddd;

            border-radius: 10px;

            box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.1);

            text-align: center;

        }

        img {

            max-width: 100%;

            height: auto;

            margin-bottom: 15px;

            border-radius: 10px;

        }

        h2 {

            color: #333;

        }

        p {

            font-size: 16px;

        }

        .back-btn {

            display: inline-block;

            padding: 10px 20px;

            margin-top: 20px;

            text-decoration: none;

            background-color: #007bff;

            color: white;

            border-radius: 5px;

        }

        .back-btn:hover {

            background-color: #0056b3;

        }

    </style>

</head>

<body>

 

    <div class="event-container">

        <h2><?php echo htmlspecialchars($title); ?></h2>

       

        <?php if (!empty($image)) { ?>

            <img src="../uploads/<?php echo htmlspecialchars($image); ?>" alt="Event Image">

        <?php } ?>

       

        <p><strong>Date:</strong> <?php echo htmlspecialchars($event_date); ?></p>

        <p><strong>Location:</strong> <?php echo htmlspecialchars($location); ?></p>

        <p><strong>Description:</strong> <?php echo nl2br(htmlspecialchars($description)); ?></p>

 

        <a href="event_list.php" class="back-btn">🔙 Back to Events</a>

    </div>

 

</body>

</html>

 

<?php

// Close database connection

mysqli_stmt_close($stmt);

mysqli_close($conn);

?>


📌 Explanation of the Code:

✅ Fetches event details from the database based on id.
✅ Uses mysqli_prepare() to prevent SQL injection.
✅ Displays event title, date, location, description, and image.
✅ Provides a "Back to Events" button to return to event_list.php.
✅ Applies basic styling for a clean display.


📌 How to Use

1.   Ensure the database and events table exist.

2.   Add new events using add_event.php.

3.   Navigate to event_list.php to view all events.

4.   Click on an event to view details using view_event.php?id=EVENT_ID.


 

Post a Comment

0Comments

Post a Comment (0)