INSERT RECORDS TO MYSQL DATABASE THRU PHP API FROM JAVASCRIPT

 students.php

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

  class Student {
    function login($json){
      include "connection-pdo.php";
   }

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


  }

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

?>

 

 index.js

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

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

const displayStudents = async() =>{
  //GET
 

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

  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>
      </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>
      `;
    tbody.appendChild(row);
  });
  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
    const 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
  });

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

}



 courses.php

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

  class Course {

    function getCourses(){
      include "connection-pdo.php";

      $sql = "SELECT crs_id, crs_title
              FROM tblcourses
              ORDER BY crs_title";
      $stmt = $conn->prepare($sql);
      $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'] : "";
  }

  $course = new Course();
  switch($operation){
    case "getCourses":
      echo $course->getCourses();
      break;
    }

?>

 

 index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>JS Modules</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script type="module" src="./js/index.js"></script>
  </head>
  <body>
    <div id="header-div"><h1 id="header-text">STUDENTS DATABASE</h1></div>
    <div id="main-div">
      <div id="input-div">
        <input type="text" id="school-id" placeholder="School ID"/>
        <input type="text" id="last-name" placeholder="Last Name"/>
        <input type="text" id="first-name" placeholder="First Name"/><br/>
        <select id="course"></select>
        <input type="date" id="birth-date" placeholder="Birthday"/><br/>
        <input type="text" id="address" placeholder="Address"/>
        <input type="number" id="balance" placeholder="Balance"/><br/>
        <button type="button" id="btn-submit">Submit</button><br/><br/>
      </div>
      <div id="table-div">

      </div>
    </div>
    <div id="footer-div"></div>
  </body>
</html>




 

 

 

 

 

No comments:

Post a Comment

INSERT RECORDS TO MYSQL DATABASE THRU PHP API FROM JAVASCRIPT

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