Add a Task

Learn how to work with tasks.

The task form

We’ll create a new file called task.php from project.php. Let’s add the form:

 <label for="project">Project</label>
 <select name="project" id="project">
   <option value="">Select a project</option>
   <!-- options here -->
 </select>
 <label for="title">Title</label>
 <input type="text" placeholder="New task" name="title" id="title">
 <label for="date">Date</label>
 <input type="date" placeholder="New task" name="date" id="date">
<label for="time">Time</label>
<input type="number" name="time" id="time">

<!-- options here --> will be replaced by the project titles, which will be fetched from the projects table.

On top of the file, inside the try/catch block, we will fetch data like this:

$sql = 'SELECT * FROM projects ORDER BY title';
$get_project_list = $connection->query($sql)->fetchAll();

We will replace the comment written above with this:

<?php foreach ($get_project_list as $item) { ?>
<option value="<?php echo $item['id'] ?>"><?php echo $item['title'] ?></option>
<?php } ?>

Form handling

Next, we’ll handle the form submission.

The full code after $get_project_list should look like this:

if (isset($_POST['submit'])) {
            $id = trim($_POST['project']);
            $title = trim($_POST['title']);
            $date = $_POST['date'];
            $time = $_POST['time'];

            $sql =  'INSERT INTO tasks(project_id, title, date_task, time_task) VALUES(:id, :title, :date, :time)';
            $statement = $connection->prepare($sql);

            if (empty($id) || empty($title) || empty($date) || empty($time)) {
                $error_message = "One or more fields empty";
            } else {
                $new_project = array(
                    'id' => $id,
                    'title' => $title,
                    'date' => $date,
                    'time' => $time
                );

                $statement->execute($new_project);

                $confirm_message = 'Added successfully';
            }}

Run the application

Now let’s run our code.

In case of success, we’ll get this image:

Get hands-on with 1400+ tech skills courses.