Simple To-Do List App

Suman KhatriSuman Khatri
5 min read

Introduction

This is a simple To-Do List application built with PHP and MySQL. The app allows users to add, update, complete, and delete tasks in a structured way.

Features

  • Add tasks

  • Mark tasks as completed

  • Update tasks

  • Delete tasks

  • Display tasks in a table

Prerequisites

Make sure you have the following installed:

  • PHP (>=7.0)

  • MySQL

  • Apache Server (XAMPP, WAMP, or LAMP recommended)

  • Bootstrap (included via CDN)

Step 1: Database Setup

  1. Open phpMyAdmin.

  2. Create a new database named todolist.

  3. Run the following SQL command to create the tasks table:

CREATE DATABASE todolist;

USE todolist;

CREATE TABLE tasks (
    id INT AUTO_INCREMENT PRIMARY KEY,
    task VARCHAR(255) NOT NULL,
    status ENUM('pending', 'completed') DEFAULT 'pending'
);

Table Constraints:

  • Primary Key: id ensures each task has a unique identifier.

  • Auto Increment: id automatically increases for each new record.

  • NOT NULL: The task field must have a value.

  • ENUM Constraint: status is restricted to either 'pending' or 'completed'.

Step 2: Database Connection

Create a file named db.php and add the following code:

<?php
$conn = mysqli_connect("localhost", "root", "", "todolist");
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
?>
  • mysqli_connect(host, username, password, database)
    This function is used to establish a connection to the MySQL server. It takes four parameters:

    • "localhost" → The hostname where the MySQL server is running. "localhost" is used when MySQL is hosted on the same machine.

    • "root" → The MySQL username. "root" is the default user for local development.

    • "" → The password field. Since no password is provided, it assumes the MySQL root user has no password (common in local environments).

    • "todolist" → The name of the database to connect to.

  • If the connection is successful, $conn will store the connection resource, which can be used to execute queries.

Step 3: To-Do List Application Code

Create a file named index.php and add the following:

<?php
include 'db.php';

// Add Task
if (isset($_POST['add'])) {
    $task = $_POST['task'];
    mysqli_query($conn, "INSERT INTO tasks (task) VALUES ('$task')");
}

// Mark as Completed
if (isset($_GET['complete'])) {
    $id = $_GET['complete'];
    mysqli_query($conn, "UPDATE tasks SET status='completed' WHERE id=$id");
}

// Delete Task
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    mysqli_query($conn, "DELETE FROM tasks WHERE id=$id");
    header("Location: index.php");
}

// Update Task
if (isset($_POST['update'])) {
    $id = $_POST['id'];
    $task = $_POST['task'];
    mysqli_query($conn, "UPDATE tasks SET task='$task' WHERE id=$id");
    header("Location: index.php");
}

// Fetch All Tasks
$result = mysqli_query($conn, "SELECT * FROM tasks ORDER BY id DESC");
?>

Explanation of the Code

  1. Includes Database Connection

    • Imports db.php to establish a database connection.
  2. Adding a Task

    • Checks if the add button was clicked.

    • Retrieves user input and inserts it into the tasks table.

  3. Marking a Task as Completed

    • Checks if a task completion request is received via GET.

    • Updates the task status to 'completed' in the database.

  4. Deleting a Task

    • Checks if a delete request is received via GET.

    • Deletes the corresponding task from the database.

    • Redirects to index.php after deletion.

  5. Updating a Task

    • Checks if an update request is received via POST.

    • Updates the task description in the database.

    • Redirects to index.php after updating.

  6. Fetching All Tasks

    • Retrieves all tasks from the database, ordered by the latest entries.

Step 4: Frontend (HTML + Bootstrap)

Add the following to index.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Simple To-Do List</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
    <h2 class="text-center">To-Do List</h2>

    <form method="POST" class="mb-3">
        <div class="input-group">
            <input type="text" name="task" class="form-control" required placeholder="Enter task">
            <button type="submit" name="add" class="btn btn-primary">Add Task</button>
        </div>
    </form>

    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Task</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($row = mysqli_fetch_assoc($result)) { ?>
                <tr>
                    <td><?= $row['task']; ?></td>
                    <td>
                        <?= $row['status'] == 'completed' ? '<span class="badge bg-success">Completed</span>' : '<span class="badge bg-warning">Pending</span>'; ?>
                    </td>
                    <td>
                        <a href="index.php?complete=<?= $row['id']; ?>" class="btn btn-white btn-sm"></a>
                        <a href="index.php?delete=<?= $row['id']; ?>" class="btn btn-white btn-sm"></a>
                        <button class="btn btn-sm" onclick="editTask(<?= $row['id']; ?>, '<?= $row['task']; ?>')"></button>
                    </td>
                </tr>
            <?php } ?>
        </tbody>
    </table>
</div>

<!-- Edit Task Modal -->
<div id="editModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Task</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form method="POST">
                    <input type="hidden" name="id" id="editId">
                    <div class="mb-3">
                        <input type="text" name="task" id="editTask" class="form-control" required>
                    </div>
                    <button type="submit" name="update" class="btn btn-primary">Update Task</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    function editTask(id, task) {
        document.getElementById("editId").value = id;
        document.getElementById("editTask").value = task;
        new bootstrap.Modal(document.getElementById("editModal")).show();
    }
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Explanation of the Code

  1. HTML Structure & Bootstrap

    • Uses Bootstrap for styling and layout.

    • Displays a simple To-Do List with a form, table, and modal.

  2. Adding Tasks

    • A form allows users to enter and submit tasks.

    • The task is sent via POST to be stored in the database.

  3. Displaying Tasks

    • Fetches tasks from the database and displays them in a table.

    • Shows status badges (Pending or Completed).

  4. Actions (Complete, Delete, Edit)

    • ✔ (Complete): Marks a task as completed using a GET request.

    • ❌ (Delete): Removes the task using a GET request.

    • ✏ (Edit): Opens a Bootstrap modal to update a task.

  5. Edit Task Modal

    • A hidden pop-up form for editing a task.

    • Prefills task details and submits updates via POST.

  6. JavaScript for Modal Handling

    • Uses Bootstrap’s modal component to open the edit form dynamically.
  7. Bootstrap & JavaScript CDN

    • Loads Bootstrap for styling and modals functionality.

Step 5: Running the Application

  1. Start Apache and MySQL in XAMPP/WAMP.

  2. Place the project folder inside htdocs (XAMPP) or www (WAMP).

  3. Open http://localhost/todolist/index.php in your browser.

  4. Add, complete, update, or delete tasks.

Conclusion

This project demonstrates a basic CRUD (Create, Read, Update, Delete) functionality in PHP and MySQL. You can enhance it by adding user authentication, categories, or due dates.


Happy coding! 🚀

0
Subscribe to my newsletter

Read articles from Suman Khatri directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Suman Khatri
Suman Khatri

I am Suman Khatri, a passionate full-stack developer specializing in React, Node.js, TypeScript, Prisma, and NestJS. With a strong foundation in modern web technologies, I craft dynamic and responsive applications that deliver seamless user experiences.