ADD, EDIT and DELETE

Prerequisite: Basic Understanding HTML, CSS, PHP and MySQL.

In this project:

  • Add records to the database.                                                                                     
  • Edit the information in added records.                                                                      
  • Delete a particular record.

index.php ⬇

<?php
    include_once 'includes/conn.php';    
    if(isset($_GET['action']) && $_GET['action'] == "edit" && is_numeric($_GET['id'])) {
        $id = $_GET['id'];
        $sql = "SELECT * FROM records WHERE id = '".$id."'";
        $exe = mysqli_query($con, $sql);
        $rec = mysqli_num_rows($exe);
        if ($rec > 0) {
            $row = mysqli_fetch_assoc($exe);
            $name = $row['name'];
            $email = $row['email'];
            $gender = $row['gender'];
            $reviews = $row['reviews'];
            $ID = $row['id'];
        }        
    } else if(isset($_GET['action']) && $_GET['action'] == "delete" && is_numeric($_GET['id'])){
        $id = $_GET['id'];
        $sql = "DELETE FROM records WHERE id = '".$id."'";
        $exe = mysqli_query($con, $sql);
    }
?>
<!DOCTYPE html> 
<html lang="en"> 
    <head> 
        <meta charset="UTF-8"> 
        <title>User Form</title>
        <script src="js/jquery.min.js"></script>      
        <script>
                function action(id, val){
                    $("#action_val").value = val;
                    document.getElementById('form_'+id).submit();
                } 
        </script>
        <style>
            sup{color:red}
        </style>
    </head>
    <body>
        <div class="form__block" >
            <?php
                if(isset($_SESSION['msg']) && $_SESSION['msg'] != ''){
                    echo "<p>".$_SESSION['msg']."</p>";
                    unset($_SESSION['msg']);
                }
            ?>
         <form action="process.php" method="POST" id="Userform">
            <label>Name<sup>*</sup></label>
            <input type="text" name="name" id="name" value="<?=isset($name)?$name:''?>" />
            <label>Email<sup>*</sup></label>
            <input type="text" name="email" id="email" value="<?=isset($email)?$email:''?>" />
            <label>Gender<sup>*</sup></label>
            <input type="radio" name="gender" value="female" <?php  if(!isset($gender) || ((isset($gender) && $gender == 'female'))){ 
       echo 'checked="checked"';                                                                                    
 }else{
       echo '';                                                                                   
} ?>/> Female
            <input type="radio" name="gender" value="male" <?php  if(!isset($gender) || ((isset($gender) && $gender == 'male'))){ 
       echo 'checked="checked"';                                                                                    
 }else{
       echo '';                                                                                   
} ?> /> Male<br>            
          <label>Reviews</label>
          <textarea rows="3" cols="23" name="reviews" id="reviews">      
                 <?=isset($reviews)?$reviews:''?>
          </textarea>
          <input type="hidden" name="recordID" value="<?=(isset($ID) && is_numeric($ID))?$ID : ''?>">
          <input type="submit" name="submit" value="SUBMIT" id="form_submit">
       </form>
     </div>
     <div style="margin-top: 50px">
        <table cellpadding="10" border="1" cellspacing="0">
            <tr>
               <th>ID</th>
               <th>Name</th>
               <th>Email</th>
               <th>Gender</th>
               <th>Reviews</th>
               <th colspan="2">Action</th>
            </tr>
         <?php
             $sql = "SELECT * FROM records ORDER BY id";
             $result = mysqli_query($con, $sql);
             if($result->num_rows > 0){
               while($row = $result->fetch_assoc()){
                   echo '<tr>';
                   echo '<td>'.$row['id'].'</td>';
                   echo '<td>'.$row['name'].'</td>';
                   echo '<td>'.$row['email'].'</td>';
                   echo '<td>'.$row['gender'].'</td>';
                   echo '<td>'.$row['reviews'].'</td>';
                   echo '<td><input type="hidden" name="action_val" id="action_val" value="">';
                   echo '<a href="index.php?action=edit&id='.$row['id'].'")>Edit</a></td>';
                   echo '<td><a href="index.php?action=delete&id='.$row['id'].'")> Delete</a></td>';
                   echo '</tr>';
                }
              }            
            ?>
          </table>
       </div>
    </body>    
</html>

Run index.php file in your browser to get the following output.

 

Code Explanation of index.php

include_once 'includes/conn.php';

• Connection file is included which includes the query to connect to the database.

<link rel="stylesheet" type="text/css" href="css/style.css">

Style.css file is attached to provide some styles to our page.

<script src="js/jquery.js"></script>

• It is necessary to include jQuery file inorder to use jquery functions. You can download it form https://jquery.com.

 

<form action="process.php" method="POST" id="Userform">
      <label>Name<sup>*</sup></label>
      <input type="text" name="name" id="name" value="<?=isset($name)?$name:''?>" />
      <label>Email<sup>*</sup></label>
      <input type="text" name="email" id="email" value="" />
      <label>Gender<sup>*</sup></label>
      <input type="radio" name="gender" value="female" /> Female
      <input type="radio" name="gender" value="male" /> Male<br>            
      <label>Reviews</label>
      <textarea rows="3" cols="23" name="reviews" id="reviews"> </textarea>
      <input type="hidden" name="recordID" value="">
      <input type="submit" name="submit" value="SUBMIT" id="form_submit">
 </form>

DESCRIPTION

1. A user form with “id=Userform”  has been created with four fields and one submit button.

2. Each field is given an id and name attribute with required value. for example :

<input type="text" name="name" id="name">

Where, 

• name input field is given name=”name” and id=”name”

• Name attributes are posted to the server while form submission and  Id attribute is used to perform JS validation

3. Button is also given an id “form_submit”, when the form is submitted, then it goes to process.php.      

<form action="process.php" method="POST" id="Userform">

             We are posting the values via HTTP POST method.

EXPLANATION OF EDIT RECORD CODE IN INDEX.PHP FILE

echo '<a href="index.php?action=edit&id='.$row['id'].'")>Edit</a></td>';

When user clicks the Edit link, the user is moved to index.php file with two query string variables i.e. action=edit and the primary ID of the record to be edited.

  • If action=edit and an ID is set, then
if(isset($_GET['action']) && $_GET['action'] == "edit" && is_numeric($_GET['id'])) {
        $id = $_GET['id'];
        $sql = "SELECT * FROM records WHERE id = '".$id."'";
        $exe = mysqli_query($con, $sql);
        $rec = mysqli_num_rows($exe);
        if ($rec > 0) {
            $row = mysqli_fetch_assoc($exe);
            $name = $row['name'];
            $email = $row['email'];
            $gender = $row['gender'];
            $reviews = $row['reviews'];
            $ID = $row['id'];
        }   
} 

The particular record is fetched and the recorded values are stored in local variables which are further displayed in Userform. For example:

<input type="text" name="name" id="name" value="<?=isset($name)?$name:''?>" />

The record is updated using UPDATE command as is mentioned in process.php file.

 EXPLANATION OF DELETE RECORD CODE IN INDEX.PHP FILE

echo '<a href="index.php?action=delete&id='.$row['id'].'")>Delete</a></td>';

When user clicks the Delete link, the user is moved to index.php file with two query string variables i.e. action=delete and the primary ID of the record to be deleted.

  • If action=delete and an ID is set, then
if(isset($_GET['action']) && $_GET['action'] == "delete" && is_numeric($_GET['id'])){
        $id = $_GET['id'];
        $sql = "DELETE FROM records WHERE id = '".$id."'";
        $exe = mysqli_query($con, $sql);
    }

The record with that particular primary ID is deleted using DELETE command. 


Code Explanation of process.php

 

<?php
    include_once 'includes/conn.php';
    if(isset($_POST['submit']) && $_POST['submit'] == "SUBMIT"){
        $name = trim($_POST['name']);
        $email = trim($_POST['email']);
        $gender = $_POST['gender'];
        $reviews = $_POST['reviews'];
        $ID = $_POST['recordID'];
        if($name != '' && $email != ''){
            if(is_numeric($ID) && $ID > 0){
                $sql = "UPDATE records 
                            SET name = '".$name."', email = '".$email."', gender = '".$gender."', reviews = '".$reviews."'
                            WHERE id = '".$ID."'";
                $result = mysqli_query($con, $sql);
                $newID = $ID;
            }else{
                $sql = "INSERT INTO records(id, name, email, gender, reviews, created_at)
                            VALUES('','".$name."', '".$email."', '".$gender."', '".$reviews."', '".date('Y-m-d H:i:s')."')";
                $result = mysqli_query($con, $sql);
                $newID = mysqli_insert_id($con);
            }            
        }else{
            $_SESSION['msg'] = "Please fill name and email properly.";
            header("Location:index.php");
            die();
        }        
        if($newID > 0){
            $_SESSION['new_id'] = $newID;
            $_SESSION['msg'] = "Record Inserted Successfully";
            header("Location:index.php");
            die();
        }
    }
 ?>

DESCRIPTION

  • Connection file is included to get connected to the “db” database.
    if(isset($_POST['submit']) && $_POST['submit'] == "SUBMIT"){

        if submit button of Userform is pressed then the control is transferred to the if block.

  • All the posted variables are stored in local variables.
  • If $name and $email are not empty, only then the sql queries are executed, otherwise, the error message is stored in session variable. 
if(is_numeric($ID) && $ID > 0){
                $sql = "UPDATE records 
                            SET name = '".$name."', email = '".$email."', gender = '".$gender."', reviews = '".$reviews."'
                            WHERE id = '".$ID."'";
                $result = mysqli_query($con, $sql);
                $newID = $ID;
            }else{
                $sql = "INSERT INTO records(id, name, email, gender, reviews, created_at)
                            VALUES('','".$name."', '".$email."', '".$gender."', '".$reviews."', '".date('Y-m-d H:i:s')."')";
                $result = mysqli_query($con, $sql);
                $newID = mysqli_insert_id($con);

If the edit button is pressed and we already have posted the primary ID, then the update command will be executed otherwise it will insert a new row.

Values are inserted in users tables according to the syntax:

  INSERT INTO tablename (columns…) VALUES (values….)


Summary

In this project, we have learned to add, edit and delete records using PHP.

  • HTML and CSS are used to create the layout of webpage.
  • Userform is used to add new and edit the old records in the database.
  • Entered records displayed in table with edit and delete button at the end of each record.
  • Messages are displayed on webpage accordingly. 

 

Help Us to Improve our content

Let's Talk
Go back to Previous Course