DELETE A RECORD FROM MYSQL DATABASE USING VANILLA JAASCRIPT WITH API CODED IN PHP

 Code as used in the video:

delete.js

export const deleteModal = async (studId, refreshDisplay) => {
  document.getElementById("blank-modal-title").innerText = "Confirm Delete";

  const student = await getStudentDetails(studId);
  let myHtml = `
        <table class="table table-sm">
          <tr>
            <td>School ID</td>
            <td>${student[0].stud_school_id}</td>
          </tr>
          <tr>
            <td>Last Name</td>
            <td>${student[0].stud_last_name}</td>
          </tr>
          <tr>
            <td>First Name</td>
            <td>${student[0].stud_first_name}</td>
          </tr>
          <tr>
            <td>Address</td>
            <td>${student[0].stud_address}</td>
          </tr>
          <tr>
            <td>Birthday</td>
            <td>${student[0].stud_dob}</td>
          </tr>
          <tr>
            <td>Course</td>
            <td>${student[0].crs_code}</td>
          </tr>
          <tr>
            <td>Balance</td>
            <td>${student[0].stud_balance}</td>
          </tr>
        </table>
    `;
  document.getElementById("blank-main-div").innerHTML = myHtml;

  const modalFooter = document.getElementById("blank-modal-footer");
  myHtml = `
      <div class="btn-group" role="group">
        <button type="button" class="btn btn-danger btn-sm w-100 me-2 btn-delete">Delete</button>
        <button type="button" class="btn btn-secondary btn-sm w-100" data-bs-dismiss="modal">Close</button>
      </div>
   `;
  modalFooter.innerHTML = myHtml;

  const myModal = new bootstrap.Modal(document.getElementById("blank-modal"), {
    keyboard: true,
    backdrop: "static",
  });

  modalFooter.querySelector(".btn-delete").addEventListener("click", async() => {
    if(await deleteRecord(student[0].stud_id) == 1){
      refreshDisplay();
      alert("Record has been deleted!");
      myModal.hide();
    }else{
      alert("ERROR");
    };
  });

  myModal.show();
};

const getStudentDetails = async (studId) => {
  const params = {
    operation: "getStudent",
    json: JSON.stringify({ studId: studId }),
  };
  const response = await axios.get(
    `${sessionStorage.baseAPIUrl}/students.php`,
    {
      params: params,
    }
  );
  return response.data;
};

const deleteRecord = async (studId) => {
  const params = {
    operation: "deleteStudent",
    json: JSON.stringify({ studId: studId }),
  };
  const response = await axios.get(
    `${sessionStorage.baseAPIUrl}/students.php`,
    {
      params: params,
    }
  );
  console.log(response.data)
  return response.data;
};


 

 index.js

import { viewModal } from "./modules/view.js";
import { updateModal } from "./modules/update.js";
import { deleteModal } from "./modules/delete.js";

const baseApiUrl = "http://localhost/jslecture/api";

sessionStorage.setItem("baseAPIUrl", baseApiUrl);
let courses = [];

document.addEventListener("DOMContentLoaded", () => {
  displayCourses();
  displayStudents();
  document.getElementById("btn-submit").addEventListener("click", () => {
    insertStudent();
  });
});

const displayStudents = async () => {
  const response = await axios.get(`${baseApiUrl}/students.php`, {
    params: { operation: "getAllStudents" },
  });

  if (response.status == 200) {
    displayStudentsTable(response.data);
  } else {
    alert("Error!");
  }
};

const displayStudentsTable = (students) => {
  const tableDiv = document.getElementById("table-div");
  tableDiv.innerHTML = "";

  const table = document.createElement("table");

  table.classList.add("table", "table-hover", "table-striped", "table-sm");

  const thead = document.createElement("thead");
  thead.innerHTML = `
      <tr>  
        <th>ID</th>
        <th>LAST NAME</th>
        <th>FIRST NAME</th>
        <th>COURSE</th>
        <th>ADDRESS</th>
        <th>ACTION</th>
      </tr>
    `;
  table.appendChild(thead);

  const tbody = document.createElement("tbody");
  students.forEach((student) => {
    let row = document.createElement("tr");
    row.innerHTML = `
        <td>${student.stud_school_id}</td>
        <td>${student.stud_last_name}</td>
        <td>${student.stud_first_name}</td>
        <td>${student.crs_code}</td>
        <td>${student.stud_address}</td>
        <td>
          <button type='button' class='btn btn-primary btn-sm btn-view'>View</button>
          <button type='button' class='btn btn-success btn-sm btn-update'>Update</button>
          <button type='button' class='btn btn-danger btn-sm btn-delete'>Delete</button>
        </td>

      `;
    tbody.appendChild(row);
    row.querySelector(".btn-view").addEventListener("click", () =>{
      viewModal(student.stud_id);
    });
    row.querySelector(".btn-update").addEventListener("click", () =>{
      updateModal(student.stud_id, courses, displayStudents);
    });
    row.querySelector(".btn-delete").addEventListener("click", () =>{
      deleteModal(student.stud_id, displayStudents);
    });
  });
  table.appendChild(tbody);

  tableDiv.appendChild(table);
};

const displayCourses = async () => {
  const select = document.getElementById("course");

  const response = await axios.get(`${baseApiUrl}/courses.php`, {
    params: { operation: "getCourses" },
  });
  if (response.status == 200) {
    //display courses in the select element
    courses = response.data;
    courses.forEach((course) => {
      let option = document.createElement("option");
      option.innerText = course.crs_title;
      option.value = course.crs_id;
      select.appendChild(option);
    });
  } else {
    alert("Error!");
  }
};

const insertStudent = async () => {
  const jsonData = {
    schoolId: document.getElementById("school-id").value,
    lastName: document.getElementById("last-name").value,
    firstName: document.getElementById("first-name").value,
    courseId: document.getElementById("course").value,
    address: document.getElementById("address").value,
    dob: document.getElementById("birth-date").value,
    balance: document.getElementById("balance").value,
  };

  const formData = new FormData();
  formData.append("operation", "insertStudent");
  formData.append("json", JSON.stringify(jsonData));

  const response = await axios({
    url: `${baseApiUrl}/students.php`,
    method: "POST",
    data: formData,
  });


  if (response.data == 1) {
    displayStudents();
    alert("Student Successfully save!");
  } else {
    alert("ERROR");
  }
};


 

 students.php

<?php
  header('Content-Type: application/json');
  header("Access-Control-Allow-Origin: *");

  class Student {
    function getAllStudents(){
      //connect to the database
      include "connection-pdo.php";

      $sql = "SELECT a.*, b.crs_code
              FROM tblstudents a INNER JOIN tblcourses b
              ON a.stud_course_id = b.crs_id
              ORDER BY a.stud_last_name";
      $stmt = $conn->prepare($sql);
      $stmt->execute();
      $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);

      return json_encode($rs);
    }

    function insertStudent($json){
      include "connection-pdo.php";

      $json = json_decode($json, true);
      $sql = "INSERT INTO tblstudents(stud_school_id, stud_last_name, stud_first_name, stud_course_id,
        stud_address, stud_dob, stud_balance)
        VALUES(:schoolId, :lastName, :firstName, :courseId, :address, :dob, :balance)";
      $stmt = $conn->prepare($sql);
      $stmt->bindParam(":schoolId", $json['schoolId']);
      $stmt->bindParam(":lastName", $json['lastName']);
      $stmt->bindParam(":firstName", $json['firstName']);
      $stmt->bindParam(":courseId", $json['courseId']);
      $stmt->bindParam(":address", $json['address']);
      $stmt->bindParam(":dob", $json['dob']);
      $stmt->bindParam(":balance", $json['balance']);
      $stmt->execute();

      $returnValue = 0;
      if($stmt->rowCount() > 0){
        $returnValue = 1;
      }

      return json_encode($returnValue);
    }

    function getStudent($json){
      include "connection-pdo.php";
      $json = json_decode($json, true);

      $sql = "SELECT a.*, b.crs_code
              FROM tblstudents a INNER JOIN tblcourses b
              ON a.stud_course_id = b.crs_id
              WHERE a.stud_id = :studId";
      $stmt = $conn->prepare($sql);
      $stmt->bindParam(":studId", $json['studId']);
      $stmt->execute();
      $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);

      echo json_encode($rs);
    }

    function updateStudent($json){
      include "connection-pdo.php";

      $json = json_decode($json, true);
      $sql = "UPDATE tblstudents SET stud_school_id = :schoolId, stud_last_name=:lastName,
                stud_first_name=:firstName, stud_course_id=:courseId,
                stud_address=:address, stud_dob=:dob, stud_balance=:balance
              WHERE stud_id=:studId";
      $stmt = $conn->prepare($sql);
      $stmt->bindParam(":schoolId", $json['schoolId']);
      $stmt->bindParam(":lastName", $json['lastName']);
      $stmt->bindParam(":firstName", $json['firstName']);
      $stmt->bindParam(":courseId", $json['courseId']);
      $stmt->bindParam(":address", $json['address']);
      $stmt->bindParam(":dob", $json['dob']);
      $stmt->bindParam(":balance", $json['balance']);
      $stmt->bindParam(":studId", $json['studId']);
      $stmt->execute();

      $returnValue = $stmt->rowCount() > 0 ? 1 : 0;
      return json_encode($returnValue);
    }

    function deleteStudent($json){
      include "connection-pdo.php";
      $json = json_decode($json, true);

      $sql = "DELETE FROM tblstudents
              WHERE stud_id = :studId";
      $stmt = $conn->prepare($sql);
      $stmt->bindParam(":studId", $json['studId']);
      $stmt->execute();
      $returnValue = $stmt->rowCount() > 0 ? 1 : 0;

      return json_encode($returnValue);
    }

  }

  //submitted by the client - operation and json
  if ($_SERVER['REQUEST_METHOD'] == 'GET'){
    $operation = $_GET['operation'];
    $json = isset($_GET['json']) ? $_GET['json'] : "";
  }else if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $operation = $_POST['operation'];
    $json = isset($_POST['json']) ? $_POST['json'] : "";
  }

  $student = new Student();
  switch($operation){
    case "getAllStudents":
      echo $student->getAllStudents();
      break;
    case "insertStudent":
      echo $student->insertStudent($json);
      break;
    case "getStudent":
      echo $student->getStudent($json);
      break;
    case "updateStudent":
      echo $student->updateStudent($json);
      break;
    case "deleteStudent":
      echo $student->deleteStudent($json);
      break;
    }

?>

 

 

 

 

 

No comments:

Post a Comment

DELETE A RECORD FROM MYSQL DATABASE USING VANILLA JAASCRIPT WITH API CODED IN PHP

 Code as used in the video: delete.js export const deleteModal = async ( studId , refreshDisplay ) => {   document . getElementById...