Remove Records
Sometimes updating records is not enough and we may need to delete the record.
We'll cover the following
As in the previous lesson, we’ll learn how to remove a record from the database. At the end of the lesson, our assignment will be to write code to delete a project.
The main keyword for this lesson is DELETE
.
Getting started
Below is the user story for this feature:
Title: Deleting a task
Story
As a user, we’d want to see a “Delete” button next to the task list, so that we could delete a task from the database.Acceptance Criteria
Scenario: The task that is selected for deletion should be removed from the database. Given that a user previously selected a task for deletion and we have four tasks in the list, we should have three tasks in the database.
From the user story written above, we can understand that the implementation of this feature can be divided into two tasks, the delete button, and its handler.
The delete button
The view
Let’s create our “Delete” button into a form so that we can easily handle it.
Going to views/task_list.php
, we’ll edit the code that displays the list of tasks like this:
<li>
<?php echo escape($task["title"]) ?>
<form method="post">
<input type="hidden" value="<?php echo $task["id"]; ?>" name="delete">
<input type="submit" value="Delete">
</form>
</li>
Nothing tricky here. We created a hidden input that will help us get the id
of the task.
Now, let’s handle the form.
The handler
In the controller, controllers/task_list.php
, we’ll check if the user has submitted the form. Then we’ll call the delete
function:
if (isset($_POST['delete'])) {
if (delete_task($_POST['delete'])) {
header('location: task_list.php?msg=Task+deleted');
exit;
} else {
header('location: task_list.php?msg=Couldn\'t+delete+the+task');
exit;
}
}
if (isset($_GET['msg'])) {
$error_message = $_GET['msg'];
}
We need to create the delete_task()
in the model:
function delete_task($id)
{
try {
global $connection;
$sql = 'DELETE FROM tasks WHERE id = ?';
$task = $connection->prepare($sql);
$task->bindValue(1, $id, PDO::PARAM_INT);
$task->execute();
return true;
} catch (PDOException $exception) {
echo $sql . "<br>" . $exception->getMessage();
exit;
}
}
Let’s put it all together and run the code to see how it works.
Get hands-on with 1400+ tech skills courses.