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

Rashmi Mishra
4 minute read
0



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

 

9️ Online Learning Platform

Module 1: Add Course Details

📌 Folder Structure:

│── /courses/                

   ├── add_course.php         # Add a new course 

   ├── edit_course.php        # Edit an existing course 

   ├── delete_course.php      # Delete a course 

   ├── course_list.php        # List all courses 

   ├── course_detail.php      # View single course details 

Database Table:

CREATE TABLE courses (

    id INT AUTO_INCREMENT PRIMARY KEY,

    teacher_id INT NOT NULL,

    title VARCHAR(255) NOT NULL,

    description TEXT,

    price DECIMAL(10,2) DEFAULT 0.00,

    thumbnail VARCHAR(255),

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    FOREIGN KEY (teacher_id) REFERENCES users(id) ON DELETE CASCADE

);

📌 File: courses/add_course.php

<?php

// Include database connection

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

// Handling form submission

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

    $teacher_id = $_POST['teacher_id'];

    $title = $_POST['title'];

    $description = $_POST['description'];

    $price = $_POST['price'];

    $thumbnail = $_POST['thumbnail'];

 

    // Input validation

    if (empty($teacher_id) || empty($title) || empty($price)) {

        echo "Teacher ID, title, and price are required!";

    } else {

        // Insert query

        $query = "INSERT INTO courses (teacher_id, title, description, price, thumbnail)

                  VALUES ('$teacher_id', '$title', '$description', '$price', '$thumbnail')";

 

        if ($conn->query($query) === TRUE) {

            echo "New course added successfully.";

        } else {

            echo "Error: " . $query . "<br>" . $conn->error;

        }

    }

}

 

// Close connection

$conn->close();

?>

 

<!-- Basic HTML Form for adding a course -->

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Add Course</title>

</head>

<body>

    <h2>Add a New Course</h2>

    <form action="add_course.php" method="POST">

        <label for="teacher_id">Teacher ID:</label>

        <input type="number" name="teacher_id" required><br><br>

 

        <label for="title">Course Title:</label>

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

 

        <label for="description">Description:</label>

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

 

        <label for="price">Price:</label>

        <input type="number" step="0.01" name="price" required><br><br>

 

        <label for="thumbnail">Thumbnail URL:</label>

        <input type="text" name="thumbnail"><br><br>

 

        <input type="submit" value="Add Course">

    </form>

</body>

</html>

Explanation:

1.   Database Connection - Uses MySQLi to connect to the database.

2.   Form Handling - Checks if the request method is POST, retrieves input values, and validates required fields.

3.   SQL Query Execution - Uses a raw SQL query (INSERT INTO courses) without prepared statements.

4.   HTML Form - A basic form to submit course details.

📌 File: courses/edit_course.php 

<?php

// Include database connection

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

// Get course details if 'id' is provided

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

    $course_id = $_GET['id'];

 

    $query = "SELECT * FROM courses WHERE id = '$course_id'";

    $result = $conn->query($query);

 

    if ($result->num_rows > 0) {

        $course = $result->fetch_assoc();

    } else {

        die("Course not found!");

    }

}

 

// Handling form submission

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

    $course_id = $_POST['course_id'];

    $title = $_POST['title'];

    $description = $_POST['description'];

    $price = $_POST['price'];

    $thumbnail = $_POST['thumbnail'];

 

    // Input validation

    if (empty($title) || empty($price)) {

        echo "Title and price are required!";

    } else {

        // Update query

        $query = "UPDATE courses SET

                  title = '$title',

                  description = '$description',

                  price = '$price',

                  thumbnail = '$thumbnail'

                  WHERE id = '$course_id'";

 

        if ($conn->query($query) === TRUE) {

            echo "Course updated successfully.";

        } else {

            echo "Error: " . $query . "<br>" . $conn->error;

        }

    }

}

 

// Close connection

$conn->close();

?>

 

<!-- Basic HTML Form for editing a course -->

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Edit Course</title>

</head>

<body>

    <h2>Edit Course</h2>

    <form action="edit_course.php" method="POST">

        <input type="hidden" name="course_id" value="<?php echo isset($course['id']) ? $course['id'] : ''; ?>">

 

        <label for="title">Course Title:</label>

        <input type="text" name="title" value="<?php echo isset($course['title']) ? $course['title'] : ''; ?>" required><br><br>

 

        <label for="description">Description:</label>

        <textarea name="description"><?php echo isset($course['description']) ? $course['description'] : ''; ?></textarea><br><br>

 

        <label for="price">Price:</label>

        <input type="number" step="0.01" name="price" value="<?php echo isset($course['price']) ? $course['price'] : ''; ?>" required><br><br>

 

        <label for="thumbnail">Thumbnail URL:</label>

        <input type="text" name="thumbnail" value="<?php echo isset($course['thumbnail']) ? $course['thumbnail'] : ''; ?>"><br><br>

 

        <input type="submit" value="Update Course">

    </form>

</body>

</html>

Explanation:

1.   Database Connection - Connects using MySQLi.

2.   Fetching Course Data - Retrieves course details from the database using $_GET['id'].

3.   Form Submission - Updates course details in the database using UPDATE query.

4.   HTML Form - Displays the existing data in input fields for editing.

📌 File: courses/delete_course.php 

<?php

// Include database connection

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

// Check if course ID is provided

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

    $course_id = $_GET['id'];

 

    // Delete query

    $query = "DELETE FROM courses WHERE id = '$course_id'";

 

    if ($conn->query($query) === TRUE) {

        echo "Course deleted successfully.";

    } else {

        echo "Error: " . $query . "<br>" . $conn->error;

    }

} else {

    echo "Invalid request. Course ID is required.";

}

 

// Close connection

$conn->close();

?>

Explanation:

1.   Database Connection - Connects using MySQLi.

2.   Check for Course ID - Retrieves id from the $_GET request.

3.   Delete Query Execution - Runs DELETE FROM courses WHERE id = '$course_id'.

4.   Success/Error Handling - Displays success or error messages.

courses/course_detail.php 

<?php

// Include database connection

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

// Check if course ID is provided

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

    $course_id = $_GET['id'];

 

    // Fetch course details

    $query = "SELECT * FROM courses WHERE id = '$course_id'";

    $result = $conn->query($query);

 

    if ($result->num_rows > 0) {

        $course = $result->fetch_assoc();

    } else {

        die("Course not found!");

    }

} else {

    die("Invalid request. Course ID is required.");

}

 

// Close connection

$conn->close();

?>

 

<!-- Basic HTML to display course details -->

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Course Details</title>

</head>

<body>

    <h2>Course Details</h2>

   

    <p><strong>Title:</strong> <?php echo isset($course['title']) ? $course['title'] : ''; ?></p>

    <p><strong>Description:</strong> <?php echo isset($course['description']) ? $course['description'] : 'No description available.'; ?></p>

    <p><strong>Price:</strong> $<?php echo isset($course['price']) ? $course['price'] : '0.00'; ?></p>

    <p><strong>Created At:</strong> <?php echo isset($course['created_at']) ? $course['created_at'] : ''; ?></p>

 

    <?php if (!empty($course['thumbnail'])): ?>

        <p><strong>Thumbnail:</strong></p>

        <img src="<?php echo $course['thumbnail']; ?>" alt="Course Thumbnail" width="200">

    <?php endif; ?>

 

    <br>

    <a href="courses.php">Back to Courses</a>

</body>

</html>

Explanation:

1.   Database Connection - Uses MySQLi.

2.   Retrieve Course Data - Gets course details using SELECT * FROM courses WHERE id = '$course_id'.

3.   Check for Valid Course ID - If no valid id is provided, it exits.

4.   Display Course Details - Outputs title, description, price, created date, and thumbnail (if available).

5.   Back to Courses Link - Provides navigation.

📌 File: courses/course_list.php 

<?php

// Include database connection

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

 

// Fetch all courses

$query = "SELECT * FROM courses ORDER BY created_at DESC";

$result = $conn->query($query);

 

?>

 

<!-- Basic HTML to display course list -->

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Course List</title>

</head>

<body>

    <h2>Course List</h2>

 

    <?php if ($result->num_rows > 0): ?>

        <table border="1" cellpadding="10">

            <tr>

                <th>ID</th>

                <th>Title</th>

                <th>Price</th>

                <th>Created At</th>

                <th>Actions</th>

            </tr>

            <?php while ($course = $result->fetch_assoc()): ?>

                <tr>

                    <td><?php echo $course['id']; ?></td>

                    <td><?php echo $course['title']; ?></td>

                    <td>$<?php echo $course['price']; ?></td>

                    <td><?php echo $course['created_at']; ?></td>

                    <td>

                        <a href="course_detail.php?id=<?php echo $course['id']; ?>">View</a> |

                        <a href="edit_course.php?id=<?php echo $course['id']; ?>">Edit</a> |

                        <a href="delete_course.php?id=<?php echo $course['id']; ?>" onclick="return confirm('Are you sure?');">Delete</a>

                    </td>

                </tr>

            <?php endwhile; ?>

        </table>

    <?php else: ?>

        <p>No courses available.</p>

    <?php endif; ?>

 

    <br>

    <a href="add_course.php">Add New Course</a>

 

</body>

</html>

 

<?php

// Close connection

$conn->close();

?>

Explanation:

1.   Database Connection - Uses MySQLi to connect to the database.

2.   Retrieve All Courses - Fetches all courses sorted by created_at DESC.

3.   Display Course List - Uses an HTML table to display the course details.

4.   Action Links - Provides options to View, Edit, and Delete each course.

5.   Add New Course Button - Provides a link to add a new course.

 

Post a Comment

0Comments

Post a Comment (0)