Update Records

Learn how to modify a database record in PHP.

As human beings, we often make mistakes or end up changing our minds. A good application is one that is flexible and allows users to modify what’s already been saved in the database.

Now, let’s learn how we can update a project record.

Getting started

These are the steps that we’ll follow:

  • The user will click on the project that they want to edit from the list of projects.
  • They will be redirected to the project form that’s pre-populated with the information of the project they selected.
  • They’ll click the “Update” button, once the project has been modified.
  • They’ll be redirected back to the project list.

Note: This lesson will consist of two parts. This is the first one and it focuses on the view. Let’s make our list items clickable.

Going to views/project_list.php, we’ll change the code so that it looks like this:

<li>
     <a href="../controllers/project.php?id= <?php echo $project['id']; ?>"
     >
        <?php echo escape($project["title"]) ?>
     </a>
</li>

Now we can click and be redirected to the “Add project” form from the project list. We’ll notice that we’re passing the project id in the URL.

Next, let’s go to the project view: views/project.php.

Implement code for the view

Our current view is set to “Add a project”. That’s why we have $title = 'Add Project'. Now that we want the same file to handle the update feature, we’ll add this code snippet just after the title:

if (!empty($_GET['id'])) {
    $title = "Update project";
}

In the form, we want the default values to be what the user chose from the project list. For instance, ifthe user clicks the “Learn Laravel” title, this should be the value of the input title and its category in the category field of the form.

In the form, we’ll replace the title input with this:

<input type="text" placeholder="New project" name="title" id="title" value="<?php                   echo $project_title; ?>">

The $project_title variable will be taken from the controller. For now, nothing will happen.

For the category, we’ll replace the form under the first <option> with this:

Get hands-on with 1200+ tech skills courses.