To Do List Using PHP and MySQL

PHP MySQL To do List: In this tutorial, You will learn to create a simple To-do list using PHP and MySQL step by step. So, You should read all the given points carefully. So that you can easily integrate Todo functionality into your project

Using To-do Feature, you can easily list your day-to-day task, daily schedules & other tasks. So It will be very helpful to maintain quickly your daily routine with a single click.

If you integrate this feature on your website, then You can do the following things  –

  • You can add your task by clicking the add button.
  • You can edit the task by clicking the pencil icon.
  • You can update the task by clicking the update button.
  • Even You can delete the task list by clicking the trash icon.

php mysql to do list

Create a To-Do App using PHP, MySQLi

Now, I am going to start to develop a simple to-do list from the basic level so that you can easily understand its working concept.

Learn Also –

Create a To-do list using jQuery

Create a Simple React App

1. Create To Do Directory

Before getting started it’s coding, you have to do the following things–

Create a folder structure

to-do-list/
   |__database.php
   |__to-do-form.php
   |__create-to-do.php
   |__edit-to-do.php
   |__update-to-do.php
   |__delete-to-do.php
   |__index.php
   |

2. Create To Do page

Step 2: Include the Bootstrap 5 CDN

Step 3: Also, Include the jQuery CDN

Step 4: Include the required PHP files

File Name – index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
</head>
<body>

<div class="container my-5">

  <h2>PHP To Do List</h2>
  
  <div class="row">
    <div class="col-sm-6">
        <?php
         include("database.php");
         include("delete-to-do.php");
         include("to-do-form.php");
         include("to-do-list.php");
        ?>
        
    </div>
     <div class="col-sm-6">
     </div>
  </div>

</div>

</body>
</html>

3. Create a Table for a To-Do List

Table Name – todo

CREATE TABLE `todo` (
`id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
`task` varchar(255) DEFAULT NULL
)

4. Setup MySQL Database Connection

To insert a select option value in the database, you must connect PHP to MySQL database with the help of the following query.

Where –

  • $hostName – assign the hostname.
  • $userName – assign the username of the database .
  • $password – assign the password of the database
  • $database – assign the database name.

File Name – database.php

<?php

$hostName = 'localhost';
$userName = 'root';
$password = '';
$database = 'codingstatus';

$conn = new mysqli($hostName, $userName, $password, $database);

if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
?>

5. Create To-Do Form

Create a Form to insert and update the To-Do list by doing the following points –

Step 1: Create an HTML form with the following details

 Form Label Attribute  Value
 Form  Field method post
 Task Input Filed name task
 Submit button name add/update

Step 2: Include the following files using include() method.

  • create-to-do.php
  • edit-to-do.php
  • update-to-do.php

Step 3: Call the following methods and use its values based on condition.

  • createTask()
  • editTaskById()
  • updateTaskById()

File Name – to-do-form.php

<?php
         include("create-to-do.php");
         include("edit-to-do.php");
         include("update-to-do.php");

        $editTask = editTaskById();
        $createTask = createTask();

        if(isset($_GET['edit-task'])) {
            $createTask = updateTaskById();

        }

?>
  <form method="post">    
    <p class="text-danger">
        <?php 
         echo $createTask['success']??'';
         echo $createTask['taskMsg']??''; 
         ?>
    </p>
 
    <div class="input-group mb-3">
      <input type="text" class="form-control" placeholder="Enter Something..." name="task" value="<?php echo $editTask['task']??''; ?>">
      <button type="submit" class="btn btn-primary" name="<?php echo count($editTask)?'update':'add'; ?>"><?php echo count($editTask)?'update':'add'; ?></button>
    </div>

  </form>

6. Create To Do using PHP

Now, You have to write PHP code to insert to-do list data into the database. So, You need to follow these steps –

Step 1: Crate a custom function named createTask() and write the code within it according to the next steps

Step 2:  use a connection variable $conn with global keyword. This variable is already decalred in the database.php file.

Step 3: Apply if condition with $_POST['add'] (passing to the isset() method). Where ‘add’ is the name of submit button of the to-do form.

Step 4: Get the value of task input field with $_POST['task']

Step 5: Validate the value of task input field

Step 6: Insert the task input value using MySQLi Insert Query

File Name – create-to-do.php

<?php
function createTask()
{
  global $conn; 	

  if (isset($_POST['add'])) {

  	  /* validation */
    $task = $_POST['task'];

    $data['taskMsg'] = '';
    if(empty($task)) {

    	$data['taskMsg'] = "Empty Task Field!";
    }

     $validation = false;
    if(empty($data['taskMsg'])) {
       $validation = true;
    }

     if($validation) {

     /* insert query*/
    $query  = "INSERT INTO todo";
    $query .= "(task) ";
    $query .= "VALUES ('$task')";
 
    $result = $conn->query($query);

    if ($result) {
      $data['success'] = "Task is added successfully";
    }
   }

     return $data;

   }

  
}
?>

7. Display To Do Using PHP

This code includes external functions, retrieves tasks, checks if tasks exist, iterates through tasks, and displays them with edit/delete options.

File Name – to-do-list.php

<?php
include('get-to-do.php');
$getTask = getTask(); 
?>

<?php
if(count($getTask['data'])) {
foreach($getTask['data'] as $task) {
?>

<div class="row my-3">
    <div class="col-sm-10">
        <?php
       echo $task['task'];
        ?>
    </div>
    <div class="col-sm-1">
        <a href="index.php?edit-task=<?php echo $task['id']; ?>" class="text-success text-decoration-none">
        <i class='fas fa-edit'></i>
       </a>
    </div>
    <div class="col-sm-1">
    <a href="index.php?delete-task=<?php echo $task['id']; ?>" class="text-danger text-decoration-none">
    <i class='fas fa-trash-alt'></i>

    </a>
    </div>
</div>
<hr>

<?php 
} 
}
?>

Explanation –

  • Includes an external PHP file named ‘get-to-do.php’ for additional functions.
  • Calls the getTask() function and assigns the result to the $getTask variable.
  • Checks if there are tasks by examining the count of the ‘data’ array in the returned data.
  • Initiates a loop to iterate through each task obtained from the ‘data’ array.
  • Displays each task along with edit and delete options using Bootstrap classes for styling.

8. Get To Do using PHP

The PHP code defines a function getTask() that fetches ‘id’ and ‘task’ data from a MySQL ‘todo’ table, orders it by ‘id’ in descending order, and returns the result as an associative array. The function assumes a global database connection variable $conn.

File Name – get-to-do.php

<?php
/* Fetch data */
function getTask()
{

    global $conn; 
    $data['data'] = [];

  $query  = "SELECT id, task ";
  $query .= "FROM todo ORDER BY id DESC"; 

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

    if($result->num_rows> 0) {

    	$data['data'] = $result->fetch_all(MYSQLI_ASSOC);

    }

  }
    
    return $data;
  
}

?>

Explanation –

  • The code defines a PHP function named getTask() to fetch data from a MySQL database.
  • The variable $conn is assumed to be a global variable representing the database connection.
  • An empty array $data['data'] is initialized to store the results of the database query.
  • The SQL query is constructed to select the ‘id’ and ‘task’ columns from a table named ‘todo’, ordering the results by ‘id’ in descending order.
  • The query is executed using $conn->query($query), and the result is stored in the variable $result.
  • It checks if the result is truthy (i.e., not false) to ensure the query was successful.
  • If there are rows in the result, the fetched data is stored in the $data['data'] array using $result->fetch_all(MYSQLI_ASSOC), which fetches all rows as an associative array.
  • The function returns the populated $data array, which now contains the fetched data.

9. Edit the To-Do List

The code defines a PHP function editTaskById that retrieves task data from a database based on a provided task ID obtained from the URL parameter ‘edit-task’. The function returns the fetched data

File Name – edit-to-do.php

<?php

/* edit data */
function editTaskById(){

  global $conn;
    $data=[];
  if(isset($_GET['edit-task']) && !empty($_GET['edit-task']) ) {
     
    $id = $_GET['edit-task'];
    $msg = [];

     /* sql query*/
  $query = "SELECT task ";
  $query .= "FROM todo ";
  $query .= "WHERE id=$id"; 

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

 }
 return $data; 

}	

?>

Explanation –

  • The editTaskById function is defined, and it appears to be related to editing tasks in a to-do list.
  • The global $conn; statement suggests that the function is using a global variable $conn, presumably representing a database connection.
  • An empty array $data is initialized to store information.
  • The function checks if the ‘edit-task’ parameter is set in the URL ($_GET['edit-task']) and is not empty.
  • If the condition in step 5 is true, the function proceeds to retrieve the task with the specified ID from the database.
  • The task ID is obtained from the ‘edit-task’ parameter in the URL and stored in the variable $id.
  • An empty array $msg is declared, but it is not used in the provided code.
  • A SQL query is constructed to select the ‘task’ column from a table named ‘todo’ where the ID matches the provided ID.
  • The query result is obtained using $conn->query($query).
  • The fetched data from the result is assigned to the $data variable.
  • The function returns the obtained data.

10. Update To-Do List

This PHP code defines a function updateTaskById() to update a task in a todo list. It checks for valid input, including a non-empty task and appropriate parameters. If validation passes, it constructs and executes an SQL UPDATE query, redirecting to ‘index.php’ upon success. The function returns an error message if validation fails.

File Name – update-to-do.php

<?php
function updateTaskById()
{
  global $conn; 
  
if (isset($_POST['update']) && isset($_GET['edit-task']) && !empty($_GET['edit-task'])) {
      
  $id = $_GET['edit-task'];

    $task = $_POST['task'];

    $data['taskMsg'] = '';
    $validation = false;

   if(empty($task)) {
      $data['taskMsg'] = "task Field is required";
    
    }


    if(empty($data['taskMsg'])) {
       $validation = true;
    }
     /* validation */

    if($validation) {

     /* sql query*/
    $query  = "UPDATE todo SET ";
    $query .= "task ='$task' ";
    $query .= "WHERE id =$id";

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

    if ($result) {

      echo "<script>window.location='index.php'</script>";

    } 
    /*sql query*/
    	
    }
    
    return $data;
}

  
}

?>

Explanation –

  • This PHP code defines a function named updateTaskById().
  • The function starts by checking if the ‘update’ key is set in the $_POST array and the ‘edit-task’ key is set in the $_GET array and is not empty.
  • If the conditions in step 2 are met, it extracts the task ID from the ‘edit-task’ parameter in the URL ($_GET[‘edit-task’]).
  • It then retrieves the task data from the $_POST array.
  • The function initializes an empty message variable, $data[‘taskMsg’], and a validation flag variable, $validation.
  • It checks if the task is empty and sets an error message in $data[‘taskMsg’] if true.
  • If there are no errors so far, it sets $validation to true.
  • The function then enters a block where it checks if $validation is true.
  • If $validation is true, it constructs an SQL UPDATE query to update the ‘todo’ table with the new task data where the task ID matches the provided ID.
  • The query is executed using $conn->query(), and if successful, the script redirects the user to ‘index.php’ using JavaScript.
  • The function returns the $data array, which may contain an error message if the task was empty.
  • The closing brace concludes the function definition.