HOW TO UPDATE A RECORD IN MYSQL DB THRU API PHP IN VANILLA JAVASCRIPT

update.js

export const updateModal = async (studId, courses, refreshDisplay) => {
  const myModal = new bootstrap.Modal(document.getElementById("blank-modal"), {
    keyboard: true,
    backdrop: "static",
  });

  //prepare the modal content
  document.getElementById("blank-modal-title").innerText = "Update Student Record";

  const student = await getStudentDetails(studId);

  let myHtml = `
        <table class="table table-sm">
          <tr>
            <td>School ID</td>
            <td>
              <input type="text" id="update-school-id" class="form-control" value="${student[0].stud_school_id}" />
            </td>
          </tr>
          <tr>
            <td>Last Name</td>
            <td>
              <input type="text" id="update-last-name" class="form-control" value="${student[0].stud_last_name}" />
            </td>
          </tr>
          <tr>
            <td>First Name</td>
            <td>
              <input type="text" id="update-first-name" class="form-control" value="${student[0].stud_first_name}" />
            </td>
          </tr>
          <tr>
            <td>Address</td>
            <td>
              <input type="text" id="update-address" class="form-control" value="${student[0].stud_address}" />
            </td>
          </tr>
          <tr>
            <td>Birthday</td>
            <td>
              <input type="text" id="update-birth-date" class="form-control" value="${student[0].stud_dob}" />
            </td>
          </tr>
          <tr>
            <td>Course</td>
            <td>
              ${createCourseSelect(courses, student[0].stud_course_id)}
            </td>
          </tr>
          <tr>
            <td>Balance</td>
            <td>
              <input type="number" id="update-balance" class="form-control" value="${student[0].stud_balance}" />
            </td>
          </tr>
        </table>
    `;
  document.getElementById("blank-main-div").innerHTML = myHtml;

  const modalFooter = document.getElementById("blank-modal-footer");
  myHtml = `
      <button type="button" class="btn btn-primary btn-sm w-100 btn-update">UPDATE</button>
      <button type="button" class="btn btn-secondary btn-sm w-100" data-bs-dismiss="modal">Close</button>
    `;
  modalFooter.innerHTML = myHtml;

  modalFooter.querySelector(".btn-update").addEventListener("click", async() => {
    //update student record
    if(await updateStudent(studId) == 1){
      refreshDisplay();
      alert("Student record has been successfully updated!");
      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 createCourseSelect = (courses, courseId) => {
  let myHtml = `<select id="update-course" class="form-select">`;
 
  courses.forEach(course => {
    let selected = courseId == course.crs_id ? "selected" : "";
    myHtml += `<option value="${course.crs_id}" ${selected}>${course.crs_title}</option>`;
  });

  myHtml += "</select>";
  return myHtml;
}

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

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

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


 index.js

import { viewModal } from "./modules/view.js";
import { updateModal } from "./modules/update.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", () =>{
      alert("You clicked the DELETE button");
    });
  });
  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");
  }
};


 

view.js

export const viewModal = async (studId) => {
  //prepare the modal content
  document.getElementById("blank-modal-title").innerText = "View Details";

  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 = `
      <button type="button" class="btn btn-secondary btn-sm w-100" data-bs-dismiss="modal">Close</button>
    `;
  modalFooter.innerHTML = myHtml;

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

  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;
};


 

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);

      echo 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;
      }

      echo 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;
      echo json_encode($returnValue);
    }

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

      $sql = "DELETE FROM tblstudents
              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);
    }

  }

  //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;
    }

?>

 

 

 

No comments:

Post a Comment

HOW TO UPDATE A RECORD IN MYSQL DB THRU API PHP IN VANILLA JAVASCRIPT

update.js export const updateModal = async ( studId , courses , refreshDisplay ) => {   const myModal = new bootstrap . Modal (...