Edit data in php using form and mysql

Welcome to another tutorial focused on editing data in PHP using an edit form. Before learning the edit operation, you must know how to insert data and how to fetch the inserted data from the database.  It’s because we will fetch the data from the database in a table and create an edit button with every row. When the user clicks on the update button, it will send the id to the edit form in the URL. We will use this id to fetched the data from the database to fill in the input fields of the edit form. The User will update the data that he wants. He can also update the image as well. Once the submit button is pressed the data will be updated in the database. Now let’s start the article to learn the complete update operation.

Edit data in php using edit form and MySQL
Edit data in php using edit form and MySQL

Add an update button to every row using PHP

  •  First of all, establish a connection with the database to perform CRUD operations.
  • Now fetch the data from the database in a table. 
  •   Then create an extra column in the table for the update button inside the while loop.
  •  Set the href attribute of the update button to “EditBook.php”. 
  •  Also, send the id of the row by embedding PHP script inside the href attribute after “?”. The id will be sent through the “GET” method.
  •  Use the echo statement inside the embedded script to send “Row[‘id’]” to our edit form page.

Now see the code example. I hope it will help you understand things better.

<table class="table table-bordered">
    <thead class="thead">
        <tr>
            <th scope="col">Title </th>
            <th scope="col">Author</th>
            <th scope="col">Description</th>
            <th scope="col">Date</th>
            <th scope="col">Download</th>
            <th scope="col">Update</th>
        </tr>
    </thead>
    <tbody>
        <?php
        require 'includes/db.inc.php';
        $query  = "SELECT * FROM book WHERE user_id= $user_id;";
        $result = mysqli_query($conn, $query);
        if (mysqli_num_rows($result) > 0) {
            while ($Row = mysqli_fetch_assoc($result)) {
        ?>
                <tr>
                    <td><?php
                        echo $Row['title'];
                        ?></td>
                    <td><?php
                        echo $Row['author'];
                        ?></td>
                    <td><?php
                        echo $Row['description'];
                        ?></td>
                    <td><?php
                        echo $Row['date'];
                        ?></td>
                    <td>
                        <a class="btn btn-primary my-3" href="<?php echo "uploads/" . $Row['filename']; ?>">
                            Download
                        </a>
                    </td>
                    <td>
                        <a class="btn btn-warning my-3" href="EditBook.php?id=<?php echo $Row['id']; ?>">
                            Update
                        </a>
                    </td>
                </tr>
        <?php
            }
        }
        ?>
    </tbody>
</table>

Create an Html form to edit data

  • Create an HTML form with the method attribute set to “POST”.
  •  Set the action attribute of the form to “includes/EditBook.inc.php”.
  •  Since we are updating images as well, so we also need to set the enctype attribute to “multipart/form-data”. Learn file upload in detail here.
  • Create two input text fields for the book title and author.
  • Also, create a text area for the description of the book.
  • Now add the file input field to the form as well. 
  •  Create two hidden input fields to send id and filename information to “EditBook.inc.php”.

That’s it. Our HTML form is reading. You can use bootstrap to do a little bit of designing. Now see the complete code.

<form method="POST" action="includes/EditBook.inc.php" enctype="multipart/form-data">
    <div class="form-group my-3">
        <input type="text" class="form-control" value="<?php echo $row['title'] ?> " name="title" />
    </div>
    <div class="form-group my-3">
        <input type="text" class="form-control" value="<?php echo $row['author'] ?>" name="Author" />
    </div>
    <div class="form-group my-3">
        <textarea class="form-control" rows="5" name="desc" style="resize: none;">
<?php echo $row['description'] ?>

        </textarea>
    </div>

    <div class="mb-3">
        <label for="file" class="form-label">Upload pdf or docx format book document</label>
        <input class="form-control" type="file" name="file" value="<?php echo $row['filename'] ?>" />
    </div>
    <input type="hidden" name="id" value="<?php echo $row['id']; ?>" />
    <input type="hidden" name="prevfile" value="<?php echo $row['filename']; ?>" />
    <button type="submit" name="submit" class="btn my-3 fs-5 px-4" style="background: #068a9c;">Submit</button>
</form>

Write PHP code to Edit data

  •  Establish the database connection using the database connectivity file.
  •  Start the sessions and as a good practice check if the edit form is submitted properly using the isset() function.
  •  Recieve or save the data sent through the POST method from edit form into variables.
  •  It’s also a good practice to use real_escape_string() when retrieving string data. This function escapes special characters in SQL statements.
  •  Also store the data of the post id, user id, and old file name into variables.
  •  Retrieve the new file information into variables as well.
  •  Apply a check on your form data. If any of the input field data is empty, generate an error using header() function.
  •  Now we have two cases. If the user wants to update the file then apply the following four steps.
  •   Remove the previous file from our uploads folder using the PHP unlink() function.
  •  Apply some file validation to refrain users from unwanted file uploads.
  •  Upload the file using move_uploaded_file().
  •  Execute the update query and update the database data including the filename.
  •  But if the user just wants to update data without a file then simply execute the update query without updating the filename.

We are almost done with editing data in PHP using form mysqli. Now see the update code example to understand the above steps better.

<?php
  require "db.inc.php";
  session_start();
  if (isset($_POST['submit'])) {
      $title = mysqli_real_escape_string($conn, $_POST["title"]);
      $Author = mysqli_real_escape_string($conn, $_POST["Author"]);
      $desc = mysqli_real_escape_string($conn, $_POST["desc"]);
      $id = $_POST['id'];
      $user_id = $_SESSION['id'];
      $PrevFileName = $_POST['prevfile'];
      //file information
      $file_name = $_FILES['file']['name'];
      $file_size = $_FILES['file']['size'];
      $file_tmp = $_FILES['file']['tmp_name'];
      $file_type = $_FILES['file']['type'];
      //checking if any of the input is empty
      if (empty($title) || empty($Author) || empty($desc)) {
          header("location: ../EditBook.php?error=InputEmpty");
          exit();
      }
      //if users selects a file then update query
      if (!empty($file_name)) {
          $extensions = ["docx", "pdf"];
          $FileExt = explode('.', $file_name);
          $FileActualExt = strtolower(end($FileExt));

          if (in_array($FileActualExt, $extensions) === false) {
              header("location: ../EditBook.php?error=InvalidFileFormat");
              exit();
          }

          if ($file_size > 10000000) {
              header("location: ../EditBook.php?error=InvalidFileSize");
              exit();
          }

          $FileNewName = $user_id . rand(1000, 9999) . "." . $FileActualExt;
          if (!unlink('../uploads/' . $PrevFileName)) {
              die("error while removing previous file");
          }
          move_uploaded_file($file_tmp, '../uploads/' . $FileNewName);

          $query = "UPDATE `book` SET `title`='$title',`author`='$Author',`description`='$desc',`filename`='$FileNewName' WHERE `id`='$id'";

          if (mysqli_query($conn, $query)) {
              header("location: ../EditBook.php?error=success");
          } else {
              die("error while executing the query" . mysqli_error($conn));
          }
          //if the user don't select a file then update query
      } else {
          $query = "UPDATE `book` SET `title`='$title',`author`='$Author',`description`='$desc' WHERE `id`='$id'";

          if (mysqli_query($conn, $query)) {
              header("location: ../EditBook.php?error=success");
          } else {
              die("error while executing the query" . mysqli_error($conn));
          }
      }
  } else {
      die("error while submiting the form");
  }

  mysqli_close($conn);


?>

Now it’s time to display the response(error or success messages) of the “EditBook.onc.php” page on “EditBook.php” page. The response message is sent using header() function in url. 

Display error messages received in the URL

In this tutorial, we submitted the edit form to a pure PHP file to write an edit operation script. In such a case, the response or the error and success messages need to be sent between two different pages. There are different methods to sent data between different pages. We can send it as parameters in URL, through SESSIONS and COOKIES. In this tutorial, we have sent the data in URL through the header() function. Now let’s display that error or success messages.

  • First of all, apply a check to see if the “GET[‘error’]” variable is set.
  •  If a success message is received in the GET variable then write a success message to the user.
  •  On the other hand, if an empty input message is received, generate a warning message. 
  •  Do the same for all other error messages. Learn server-side validation in detail here.

See the code to understand things better.

<?php
if (isset($_GET["error"])) {
if ($_GET["error"] == "success") {
    echo "
    <p class='alert alert-success'>
       Book Added successfully.
    </p>
 ";
}

if ($_GET["error"] == "InputEmpty") {
echo "
    <p class='alert alert-danger'>
        Warning! input Fields are Empty.
    </p>
";
}

if ($_GET["error"] == "InvalidFileFormat") {
echo "
    <p class='alert alert-danger'>
	Warning! Invalid file format. Upload only pdf or docx file.
    </p>
";
}
if ($_GET["error"] == "InvalidFileSize") {
echo "
    <p class='alert alert-success'>
	Warning! File size too big.
    </p>
 ";
}
}

?>

That is all on how to edit data in PHP using form MySQLi. Here is the end of the tutorial. I hope you found this content interesting. Thanks for reading and supporting us.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top