Wednesday, January 29, 2020

AngularJS PHP CRUD (Create,Read,Update,Delete) Operations

AngularJS PHP  CRUD (Create,Read,Update,Delete) Operations

In one of our tutorials we saw that Operation Crud uses PHP PDO with the addition Ajax, Bootstrap and Jquery Datatables. In the same way we did another web development tutorial for the crud operation here and here the crud operation using AngularJS with PHP, Bootstrap-Modal and the JQuery Datatables add-on. If you've used the JQuery Javascript library as a client-side front-end development, you can follow the CRUD operation tutorial where Ajax JQuery was used with PHP PDO, Bootstrap Modal and the Jquery Datatables plugin. On the other hand, there are many web developers who have used the AngularJS JavaScript library for their front-end web development. This tutorial is aimed at those web developers who use AngularJS instead of Jquery. This post explained how to insert, update, and delete mysql data using AngularJS with PHP.

AngularJS is an object-oriented or client-side front-end web development framework written entirely in pure JavaScript. By using AngularJS we can simplify the development of one-sided web applications.


Tutorial Summary



  • List all data in the Jquery Datatables plug-in with AngularJS
  • Add or insert new data in MySQL with AngularJS with PHP and Bootstrap Modal
  • Reads data from the MySQL database using AngularJS using PHP
  • Edit or update existing MySQL data using PHP with AngularJS
  • Remove data from the MySQL table using AngularJS using PHP



For using AngularJS with PHP for Crud operation, here we have a simple one-page application for inserting, updating and deleting data from the MySQL first and last name table using AngularJS with PHP and Bootstrap modal. Now you can develop the AngularJS PHP Crud application step by step.


Step 1 - Make Database Connection


Here we first need to create a simple tbl_sample table in the database and then connect to the PHP AngularJS application.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_sample`
--

CREATE TABLE `tbl_sample` (
  `id` int(11) NOT NULL,
  `first_name` varchar(250) NOT NULL,
  `last_name` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Indexes for table `tbl_sample`
--
ALTER TABLE `tbl_sample`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for table `tbl_sample`
--
ALTER TABLE `tbl_sample`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;


After creating the table in the MySQL database by writing the following code to the database_connection.php file, you can connect


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");



?>




Step 2 - File Structure of AngularJS PHP Crud Application


Below is a brief overview of the files used to create AngularJS PHP Crud. All files are necessary to make this application.


  • b> Angular PHP Crud application
  • angle-datatables.min.js (This is the AngularJS JavaScript library)
  • bootstrap.min.css (This is the Bootstrap stylesheet library)
  • bootstrap.min.js (This is the Bootstrap Javascript library)
  • database_connection.php (PHP file for database connection)
  • datatables.bootstrap.css (This is the Bootstrap Datatables stylesheet library)
  • fetch_data.php (This PHP file to select all data from the MySQL database)
  • index.html (This is the main page of our AngularJS Crud application.)
  • insert.php (this file for inserting, updating and deleting data)
  • jquery.dataTables.min.css (This is the Jquery Datatables stylesheet library.)
  • jquery.dataTables.min.js (This is the JQuery Datatables Javascript library.)
  • jquery.min.js (This Jquery JavaScript library)



Step 3 - Set up Index page


Now we have developed the AngularJS PHP Crud application. In this first step we want to configure the index page for this application. On the index page, we would first like to import the previous Javascript and CSS file into our index page. In the header of the index page we have to write the following HTML code to import Javascript and CSS files.


<!DOCTYPE html>
<html>
 <head>
  <title>AngularJS PHP  CRUD (Create,Read,Update,Delete) Operations</title>
  <script src="jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="jquery.dataTables.min.js"></script>
  <script src="angular-datatables.min.js"></script>
  <script src="bootstrap.min.js"></script>
  <link rel="stylesheet" href="bootstrap.min.css">
  <link rel="stylesheet" href="datatables.bootstrap.css">
 </head>
        <body ng-app="crudApp" ng-controller="crudController">
        </body>
</html>



Here in body tag we see two directives ng-app and ng-controller from AngularJS. With the instruction ng-app we defined the name of the application and with the instruction ng-controller we added the controller to our application.


Step 4 - Load Mysql Data into Jquery Datatables using AngularJS with PHP


To build the CRUD application first, we would like to list all the MySQL database data on the website. Here we used the Jquery Datatables plugin to display the data from the mysql table in raster format. This way we can easily search and sort data. We used AngularJS with PHP for server-side processing and loading data into the Jquery Datatables add-in. First of all we have a table in our index.html.


   <div class="table-responsive" style="overflow-x: unset;">
    <table datatable="ng" dt-options="vm.dtOptions" class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>First Name</th>
       <th>Last Name</th>
      </tr>
     </thead>
     <tbody>
      <tr ng-repeat="name in namesData">
       <td>{{name.first_name}}</td>
       <td>{{name.last_name}}</td>
      </tr>
     </tbody>
    </table>
   </div>


The code of the previous HTML table shows some modules for angle data tables, e.g. B. datatable and dt-options for Jquery datatables. After that, we need to write the following angular javascript code for the registration module and create the driver.


var app = angular.module('crudApp', ['datatables']);

app.controller('crudController', function($scope, $http){


We then created an AngularJS function that sends a request to the fetch_data.php page to select all the data in the mysql table tq_sample and display it using this ng-repeat directive under the table complement in the Jquery table.


      $scope.fetchData = function(){
  $http.get('fetch_data.php').success(function(data){
   $scope.namesData = data;
  });
 };


In this function, data is stored in the $ scope.namesData object, and from this object we can display data under the table with the ng-repeat statement that is included in the HTML table definition. This function must be sent to the PHP file. The following server code must be written in the PHP file in order to retrieve all data from the MySQL table and send it to the AngularJS function fetchData.


<?php

//fetch_data.php

include('database_connection.php');

$query = "SELECT * FROM tbl_sample ORDER BY id";

$statement = $connect->prepare($query);

if($statement->execute())
{
 while($row = $statement->fetch(PDO::FETCH_ASSOC))
 {
  $data[] = $row;
 }

 echo json_encode($data);
}

?>


This PHP server script searches all the data in the MySQL table and sends it back to the AngularJS function using the json_encode () function in JSON string format. This is a process of displaying data under the JQuery Datatables plug-in using AngularJS with PHP.



Step 5 - Insert or Add data in Mysql using AngularJS with PHP & Bootstrap Modal


Now we have started to discuss how we can use Bootstrap Modal with AngularJS to insert or add data to the MySQL table using PHP. So we must first write the following bootstrap warning code on the index.html page to display the success message on the website.


   <div class="alert alert-success alert-dismissible" ng-show="success" >
    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
    {{successMessage}}
   </div>


This HTML code helps us to display warning messages on the website. In this case we used the ng-show directive. This directive helps us to show and hide HTML elements on the website. And here we wrote a success message in double brackets, the value of which is shown in the model.

After that, we have to write HTML code for bootstrap mode. Because we create a form modal to insert or update existing data. Then we have to make the form modal in Bootstrap. To do this, we need to write the following code.


<div class="modal fade" tabindex="-1" role="dialog" id="crudmodal">
 <div class="modal-dialog" role="document">
     <div class="modal-content">
      <form method="post" ng-submit="submitForm()">
         <div class="modal-header">
           <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
           <h4 class="modal-title">{{modalTitle}}</h4>
         </div>
         <div class="modal-body">
          <div class="alert alert-danger alert-dismissible" ng-show="error" >
      <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
      {{errorMessage}}
     </div>
          <div class="form-group">
      <label>Enter First Name</label>
      <input type="text" name="first_name" ng-model="first_name" class="form-control" />
     </div>
     <div class="form-group">
      <label>Enter Last Name</label>
      <input type="text" name="last_name" ng-model="last_name" class="form-control" />
     </div>
         </div>
         <div class="modal-footer">
          <input type="hidden" name="hidden_id" value="{{hidden_id}}" />
          <input type="submit" name="submit" id="submit" class="btn btn-info" value="{{submit_button}}" />
           <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
         </form>
     </div>
   </div>
</div>


Let us understand this bootstrap modal code. Here we used the bootstrap modal to operate the form. Under the definition of the form, we used the ng-submit statement and defined the submitFrom () function in it. If you use this directive when form data has been submitted, this submitForm () function is called to send form data to the PHP script.

The error when checking the bootstrap warning code was used again under the "Bootstrap" body tag. In this code, we also used the ng-show statement to show and hide modal HTML elements.

Here the modal title data from the angle model were linked. In this case, the text of the modal title is dynamic and changes with different processes.

To search for form data, we used the ng-model directive here. With this directive, we can get HTML element data in AngularJS.

Finally, in bootstrap mode, the hidden label and value of the send button are defined using the data connection method.


 $scope.success = false;
 $scope.error = false;


This code hides the HTML code for the success warning and the error message of the website when it has been loaded into the browser. After that, AngularJS must work to open and close bootstrap mode. To do this, we need to write the following Javascript code.


 $scope.openModal = function(){
  var modal_popup = angular.element('#crudmodal');
  modal_popup.modal('show');
 };

 $scope.closeModal = function(){
  var modal_popup = angular.element('#crudmodal');
  modal_popup.modal('hide');
 };


After that, we need to create an "add" button in our HTML code so we have to write the following code


   <div align="right">
    <button type="button" name="add_button" ng-click="addData()" class="btn btn-success">Add</button>
   </div>


We used the ng-click directive in the button caption and defined an addData () function here. When you click this button, you execute the addData () function. So we have to write the following code for the addData () function.


  $scope.addData = function(){
  $scope.modalTitle = 'Add Data';
  $scope.submit_button = 'Insert';
  $scope.openModal();
 };


Now you need to execute the submitForm () function, which is called when the form is submitted. In this function we sent the request to insert.php. The page with the form data was submitted with the request. This function is also used to insert and update existing data. Use this function in Both operation.


  $scope.submitForm = function(){
  $http({
   method:"POST",
   url:"insert.php",
   data:{'first_name':$scope.first_name, 'last_name':$scope.last_name, 'action':$scope.submit_button, 'id':$scope.hidden_id}
  }).success(function(data){
   if(data.error != '')
   {
    $scope.success = false;
    $scope.error = true;
    $scope.errorMessage = data.error;
   }
   else
   {
    $scope.success = true;
    $scope.error = false;
    $scope.successMessage = data.message;
    $scope.form_data = {};
    $scope.closeModal();
    $scope.fetchData();
   }
  });
 };


This function has to send a request to the server script insert.php. Below is a PHP script to insert data into the mysql table using AngularJS using PHP. In this file, we used the file_get_contents () function for the data we received from the AngularJS function in JSON string format. So with json_decode () we converted to PHP array format. We also wrote a server-side validation code in this code. If the data was inserted correctly, this code sent a response to the AngularJS function in JSON string format using the json_encode () function.


<?php

//insert.php

include('database_connection.php');

$form_data = json_decode(file_get_contents("php://input"));

$error = '';
$message = '';
$validation_error = '';
$first_name = '';
$last_name = '';

if(empty($form_data->first_name))
{
 $error[] = 'First Name is Required';
}
else
{
 $first_name = $form_data->first_name;
}

if(empty($form_data->last_name))
{
 $error[] = 'Last Name is Required';
}
else
{
 $last_name = $form_data->last_name;
}

if(empty($error))
{
 if($form_data->action == 'Insert')
 {
  $data = array(
   ':first_name'  => $first_name,
   ':last_name'  => $last_name
  );
  $query = "
  INSERT INTO tbl_sample 
  (first_name, last_name) VALUES 
  (:first_name, :last_name)
  ";
         $statement = $connect->prepare($query);
  if($statement->execute($data))
  {
   $message = 'Data Inserted';
  }
 }
 else
 {
  $validation_error = implode(", ", $error);
 }

 $output = array(
  'error'  => $validation_error,
  'message' => $message
 );

echo json_encode($output);

?>




Step 6 - Edit or Update Mysql Data using AngularJS with PHP & Bootstrap Modal


After you have completed the process step by step, you can insert or add data. Now we have to deal with editing or updating existing MySQL table data with AngularJS with PHP and Bootstrap modal. We have already written the bootstrap modal code and now we don't want to create a new modal. We will use the existing bootstrap modal to edit data. First we have to write the function fetchSingleData (). This function searches for specific data based on the value of the id argument. Below you will find this AngularJS function code.


  $scope.fetchSingleData = function(id){
  $http({
   method:"POST",
   url:"insert.php",
   data:{'id':id, 'action':'fetch_single_data'}
  }).success(function(data){
   $scope.first_name = data.first_name;
   $scope.last_name = data.last_name;
   $scope.hidden_id = id;
   $scope.modalTitle = 'Edit Data';
   $scope.submit_button = 'Edit';
   $scope.openModal();
  });
 };


This function has a request to send to the insert.php file to get certain line data based on the value of the id argument. After successful receipt of the data, this function has assigned a value to the respective form field. This function also sets the hidden identification value of the hidden label, the modal title and the text of the send button. With this function we finally called the openModal () function, which opens the bootstrap mode with AngularJS.


<div class="table-responsive" style="overflow-x: unset;">
    <table datatable="ng" dt-options="vm.dtOptions" class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>First Name</th>
       <th>Last Name</th>
       <th>Edit</th>
      </tr>
     </thead>
     <tbody>
      <tr ng-repeat="name in namesData">
       <td>{{name.first_name}}</td>
       <td>{{name.last_name}}</td>
       <td><button type="button" ng-click="fetchSingleData(name.id)" class="btn btn-warning btn-xs">Edit</button></td>
      </tr>
     </tbody>
    </table>
   </div>


Here we have added another column in the table to display the Edit button on each row. Ng-click = fetchSingleData (name.id) has been added to each row edit button. This generates a dynamic ID argument value in each row function. When you click the edit button, the fetchSingleData () function is executed and you get data based on the value of the id argument and display that data in bootstrap mode with the full form.


if($form_data->action == 'fetch_single_data')
{
 $query = "SELECT * FROM tbl_sample WHERE id='".$form_data->id."'";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output['first_name'] = $row['first_name'];
  $output['last_name'] = $row['last_name'];
 }
 echo json_encode($output);
}


This is a PHP script to get a specific row of data. Here, data is stored in the output variable $ in matrix form and sent to the AngularJS function in JSON string format.

In the AngularJS function, display the same modal and bootstrap form that we used to insert data. Therefore, we don't want to write any additional code here to send the data update form. We just have to write the PHP code to update the data that we can find below.


 if($form_data->action == 'Edit')
  {
   $data = array(
    ':first_name' => $first_name,
    ':last_name' => $last_name,
    ':id'   => $form_data->id
   );
   $query = "
   UPDATE tbl_sample 
   SET first_name = :first_name, last_name = :last_name 
   WHERE id = :id
   ";
   $statement = $connect->prepare($query);
   if($statement->execute($data))
   {
    $message = 'Data Edited';
   }
  }
$output = array(
  'error'  => $validation_error,
  'message' => $message
 );
echo json_encode($output);





Step 7 - Delete or Remove Mysql Data using AngularJS with PHP


This is the last CRUD operation that AngularJS uses with PHP. Here we see how we can use AngularJS to delete or delete data from the MySQL table using PHP. To do this, we first have to run an AngularJS function deleteData (). This function is called when we click the Delete button. This function sends a PHP request script to clear data based on the value of the id argument. Below is the AngularJS function code and the HTML code to add another table column to display the dynamic delete button on each row. In the delete button there is a directive ng-click for the deleteData () function.


 $scope.deleteData = function(id){
  if(confirm("Are you sure you want to remove it?"))
  {
   $http({
    method:"POST",
    url:"insert.php",
    data:{'id':id, 'action':'Delete'}
   }).success(function(data){
    $scope.success = true;
    $scope.error = false;
    $scope.successMessage = data.message;
    $scope.fetchData();
   });
  }
 };



  <div class="table-responsive" style="overflow-x: unset;">
    <table datatable="ng" dt-options="vm.dtOptions" class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>First Name</th>
       <th>Last Name</th>
       <th>Edit</th>
       <th>Delete</th>
      </tr>
     </thead>
     <tbody>
      <tr ng-repeat="name in namesData">
       <td>{{name.first_name}}</td>
       <td>{{name.last_name}}</td>
       <td><button type="button" ng-click="fetchSingleData(name.id)" class="btn btn-warning btn-xs">Edit</button></td>
       <td><button type="button" ng-click="deleteData(name.id)" class="btn btn-danger btn-xs">Delete</button></td>
      </tr>
     </tbody>
    </table>
   </div>


Now we have to write a PHP script to delete data from the MySQL table. The previous function sent a request to delete data to the insert.php file. This file deletes or deletes a specific row of data based on the value of the id argument.


elseif($form_data->action == 'Delete')
{
 $query = "
 DELETE FROM tbl_sample WHERE id='".$form_data->id."'
 ";
 $statement = $connect->prepare($query);
 if($statement->execute())
 {
  $output['message'] = 'Data Deleted';
 }
}

echo json_encode($output);



Therefore, we discussed the step-by-step process to make AngularJS Crud Application modal with PHP and Bootstrap. Here we first loaded all the data from the mysql table into the Jquery Datatables plug-in, using AngularJS with PHP. Then we discussed how to insert or add data to the MySQL database using AngularJS PHP and Bootstrap Modal. After inserting data, we saw how to update or edit existing mysql data with AngularJS using PHP and Bootstrap, and finally we saw how we can delete or delete data using PHP with anglejs. This complete single page application uses AngularJS, PHP and Bootstrap modal, because here we can not only insert, update or delete data in the MySQL database, but also search, sort and paginate data.


Thursday, January 23, 2020

Online Examination System Project in PHP MySql

Online Examination System Project in PHP MySql

This tutorial will help you build an online exam system using a PHP script with the MySQL database. So if you are looking for an educational project or want to create a small PHP system using the MySQL database, you've come to the right place. Because in this article you will find the solution for your needs. Here we create the online exam application in PHP with the MySQL database that will help you build your educational project for the past year. And if you are a beginner PHP programmer and learn how to use a dynamic online system in PHP, this post will help you.


What is Online Examination/Test System?


In the Internet world, all tasks were done over the Internet and we decided why the exam wasn't done over the Internet. In order to convert the current examination system into a digital examination system, we have created this small project of the online examination system. If this system was developed on a professional level, it will automate our existing examination system in the digitized examination system. Less work is required in this system to operate the system. It is more precise and slower. At the same time, we can conduct more personal exams and the result will be published in the shortest possible time. Below you will find the advantages of the online examination system. When this system is implemented, the exam is not limited to four walls of the classroom, but the student can take the exam from anywhere.


Advantage of Online Examination System Project


  1. The online exam system saves the organization and students money.
  2. The online exam system saves the papar exam question securely and is directly visible to the student who took the exam.
  3. The online test system saves paper costs because the test is carried out online.
  4. The online examination system reduces the costs of delivering the questionnaire to the examination center.
  5. The online exam system saves time for both the institution that performed the behavioral test and the student who took the exam.
  6. The online examination system enables remote monitoring using the security function of this system.
  7. The online test system shortens the time of publication of the test result with the classification, since the result is generated with one click.
  8. The online exam system gives us the progress of previous exams with just one click.
  9. The online exam system offers all student information on a single platform.
  10. The online exam system offers the opportunity to take any electronic device that has Internet access.



Characteristics of Online Examamination System


Admin Side


  1. The administrator can create a new test online using the Edit and Delete function
  2. The administrator can add a question to the exam that was defined at the time the exam was created
  3. The administrator can view all exam questions using the Edit and Delete operation
  4. The administrator can view all user data that has been registered for the online exam system
  5. The administrator can view all users who have registered for a particular exam
  6. The administrator can view the result of the individual user check on the website and in PDF format
  7. The administrator can view the combined test result with user rank on the website and in PDF format

User Side



  1. New user registration for online exam with confirmation email function.
  2. The user can log on to the system with an email ID and password.
  3. The user can manage his profile details.
  4. The user can change his password.
  5. The user can view the list of available exams.
  6. The user can register for the exam.
  7. The user can take the online exam at the specified date and time.
  8. The user can view the progress of the exam for which he has registered.
  9. The user can see the test result on the website and also in PDF format.

Front end


  1. HTML 5: to create an HTML web page.
  2. jQuery - For easier use of Javascript on the website.
  3. Ajax: To perform the server operation on the client side.
  4. Bootstrap 4: to create a responsive online exam system.
  5. JQuery data table plug-in: For listing data on the website in a table format with various features such as search, classification, etc.
  6. Parsley.js: To check the form data on the client side.
  7. Bootstrap Datetimepicker - User for data and time field form data.
  8. TimeCircles: Displays the remaining exam time on the website.

Back end


  1. PHP 5.6+: to log in to the writing system
  2. MySQL: For storing system data
  3. PHPMailer - Send email after registration
  4. DomPdf: to generate the test result in PDF format

Source code Online Examination System


master/register.php


In this file, we create a registration form to set up an administrator account for the online exam system. Suppose we need multiple administrator accounts for different purposes. Here we need to create a registration form to create a new administrator account for the web based exam application. This function makes this system a completely dynamic system.
To validate a unique email address for administrator registration, we used the custom validator Parsley.js here. This validator checks certain emails that are already registered in our system or not. This validator is activated before the form is sent. If this validator is activated, it sends an Ajax request to cut the script to check whether the administrator has already registered in our database with a specific email.
Here we used Ajax to send the administrator's registration data to the server. When we click the registration button, when using the jQuery code, add the parsley attribute to check the form data. If the form data is correct, send the form data to the server using the Ajax request.


master/register.php


<?php

//register.php

include('Examination.php');

$exam = new Examination;

$exam->admin_session_public();

?>

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Online Examination System Project in PHP MySql  </title>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
   <script src="https://cdn.jsdelivr.net/gh/guillaumepotier/Parsley.js@2.9.1/dist/parsley.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
   <link rel="stylesheet" href="../style/style.css" />
</head>
<body>
 <div class="jumbotron text-center" style="margin-bottom:0; padding: 1rem 1rem;">
     <img src="logo.png" class="img-fluid" width="300" alt="Online Examination System in PHP" />
 </div>

 <div class="container">
    <div class="row">
      <div class="col-md-3">

      </div>
      <div class="col-md-6" style="margin-top:20px;">
       <span id="message"></span>
         <div class="card">
           <div class="card-header">Admin Registration</div>
           <div class="card-body">
              <form method="post" id="admin_register_form">
                    <div class="form-group">
                        <label>Enter Email Address</label>
                        <input type="text" name="admin_email_address" id="admin_email_address" class="form-control" data-parsley-checkemail data-parsley-checkemail-message='Email Address already Exists' />
                    </div>
                    <div class="form-group">
                      <label>Enter Password</label>
                      <input type="password" name="admin_password" id="admin_password" class="form-control" />
                    </div>
                    <div class="form-group">
                      <label>Enter Confirm Password</label>
                      <input type="password" name="confirm_admin_password" id="confirm_admin_password" class="form-control" />
                    </div>
                    <div class="form-group">
                      <input type="hidden" name="page" value="register" />
                      <input type="hidden" name="action" value="register" />
                      <input type="submit" name="admin_register" id="admin_register" class="btn btn-info" value="Register" />
                    </div>
                  </form>
              <div align="center">
               <a href="login.php">Login</a>
              </div>
           </div>
         </div>
      </div>
      <div class="col-md-3">

      </div>
    </div>
 </div>

</body>
</html>

<script>

$(document).ready(function(){

 window.ParsleyValidator.addValidator('checkemail', {
    validateString: function(value)
    {
      return $.ajax({
        url:"ajax_action.php",
        method:"POST",
        data:{page:'register', action:'check_email', email:value},
        dataType:"json",
        async: false,
        success:function(data)
        {
          return true;
        }
      });
    }
  });

  $('#admin_register_form').parsley();

  $('#admin_register_form').on('submit', function(event){

    event.preventDefault();

    $('#admin_email_address').attr('required', 'required');

    $('#admin_email_address').attr('data-parsley-type', 'email');

    $('#admin_password').attr('required', 'required');

    $('#confirm_admin_password').attr('required', 'required');

    $('#confirm_admin_password').attr('data-parsley-equalto', '#admin_password');

    if($('#admin_register_form').parsley().isValid())
    {
      $.ajax({
        url:"ajax_action.php",
        method:"POST",
        data:$(this).serialize(),
        dataType:"json",
        beforeSend:function(){
          $('#admin_register').attr('disabled', 'disabled');
          $('#admin_register').val('please wait...');
        },
        success:function(data)
        {
          if(data.success)
          {
            $('#message').html('<div class="alert alert-success">Please check your email</div>');
            $('#admin_register_form')[0].reset();
            $('#admin_register_form').parsley().reset();
          }

          $('#admin_register').attr('disabled', false);
          $('#admin_register').val('Register');
        }
      });
    }

  });

});

</script>


master/Examination.php


This is the main PHP class for this online exam application. Here we do the object-oriented programming of PHP PDO for the compilation logic of this online questionnaire system. In this class we have the following method, which we will use for various purposes to build the online exam system in PHP.


  1. __construct (): This is the code of the magic function that runs every time this new class object is created. Every time you create a new object, you use the object to establish a database connection with this online examination system PHP PDO class.
  2. execute_query (): This method executes SQL queries for the database operation.
  3. total_row (): This method returns the total number of rows affected after running the query. In this method, we also used the execute_query () method.
  4. send_email ($ receiver_email, $ subject, $ body): In this method we created an object of the PHPMailer class and use this method to send emails in this online exam system.
  5. Forward ($ page): This method is used to forward the page.
  6. admin_session_private (): This method checks whether the administrator has logged on to the system, whether the administrator has not logged on to the system and is trying to access the website that requires a login to the system. It will then be redirected to the administrator login page.
  7. admin_session_public () - This is another way to verify administrator login. This method checks whether the administrator has logged on to the system and tries to access the login or registration page, and then redirects to the index.php page.
  8. query_result (): This method uses the execute_query () method to execute the SQL query and return the result of the query execution in associative array format.
  9. clean_data (): This method converts special characters into an HTML entity to prevent the SQL injection.
  10. Is_exam_is_not_started ($ online_exam_id): This method is used to check the respective status of the check, since the check is pending, the check is started and the check is completed. This method returns true if the check has not yet started.
  11. Get_exam_question_limit ($ exam_id): This method returns the limit that is allowed to add questions about a particular exam.
  12. Get_exam_total_question ($ exam_id): This method returns how many questions have already been added to a particular exam.
  13. Is_allowed_add_question ($ exam_id): This method returns true if the administrator can add questions to a particular exam. Otherwise, this method returns false.
  14. execute_question_with_last_id () - This method inserts a new question into the MySQL database and returns the last inserted identification of the added question.
  15. Get_exam_id ($ exam_code): This method returns the exam identification of the value of the variable $ exam_code in the exam table.
  16. Upload_file (): This method loads the selected image into the upload folder.

master/Examination.php


<?php

class Examination
{
 var $host;
 var $username;
 var $password;
 var $database;
 var $connect;
 var $home_page;
 var $query;
 var $data;
 var $statement;
 var $filedata;

 function __construct()
 {
  $this->host = 'localhost';
  $this->username = 'root';
  $this->password = '';
  $this->database = 'online_examination';
  $this->home_page = 'http://localhost/tutorial/online_examination/';

  $this->connect = new PDO("mysql:host=$this->host; dbname=$this->database", "$this->username", "$this->password");

  session_start();
 }

 function execute_query()
 {
  $this->statement = $this->connect->prepare($this->query);
  $this->statement->execute($this->data);
 }

 function total_row()
 {
  $this->execute_query();
  return $this->statement->rowCount();
 }

 function send_email($receiver_email, $subject, $body)
 {
  $mail = new PHPMailer;

  $mail->IsSMTP();

  $mail->Host = 'smtp host';

  $mail->Port = '587';

  $mail->SMTPAuth = true;

  $mail->Username = '';

  $mail->Password = '';

  $mail->SMTPSecure = '';

  $mail->From = 'info@webslesson.info';

  $mail->FromName = 'info@webslesson.info';

  $mail->AddAddress($receiver_email, '');

  $mail->IsHTML(true);

  $mail->Subject = $subject;

  $mail->Body = $body;

  $mail->Send();  
 }

 function redirect($page)
 {
  header('location:'.$page.'');
  exit;
 }
 
 function admin_session_private()
 {
  if(!isset($_SESSION['admin_id']))
  {
   $this->redirect('login.php');
  }
 }

 function admin_session_public()
 {
  if(isset($_SESSION['admin_id']))
  {
   $this->redirect('index.php');
  }
 }

 function query_result()
 {
  $this->execute_query();
  return $this->statement->fetchAll();
 }
 
 function clean_data($data)
 {
   $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
 }
 
 function Is_exam_is_not_started($online_exam_id)
 {
  $current_datetime = date("Y-m-d") . ' ' . date("H:i:s", STRTOTIME(date('h:i:sa')));

  $exam_datetime = '';

  $this->query = "
  SELECT online_exam_datetime FROM online_exam_table 
  WHERE online_exam_id = '$online_exam_id'
  ";

  $result = $this->query_result();

  foreach($result as $row)
  {
   $exam_datetime = $row['online_exam_datetime'];
  }

  if($exam_datetime > $current_datetime)
  {
   return true;
  }
  return false;
 }
 
 function Get_exam_question_limit($exam_id)
 {
  $this->query = "
  SELECT total_question FROM online_exam_table 
  WHERE online_exam_id = '$exam_id'
  ";

  $result = $this->query_result();

  foreach($result as $row)
  {
   return $row['total_question'];
  }
 }

 function Get_exam_total_question($exam_id)
 {
  $this->query = "
  SELECT question_id FROM question_table 
  WHERE online_exam_id = '$exam_id'
  ";

  return $this->total_row();
 }

 function Is_allowed_add_question($exam_id)
 {
  $exam_question_limit = $this->Get_exam_question_limit($exam_id);

  $exam_total_question = $this->Get_exam_total_question($exam_id);

  if($exam_total_question >= $exam_question_limit)
  {
   return false;
  }
  return true;
 }

 function execute_question_with_last_id()
 {
  $this->statement = $this->connect->prepare($this->query);

  $this->statement->execute($this->data);

  return $this->connect->lastInsertId();
 }
 function Get_exam_id($exam_code)
 {
  $this->query = "
  SELECT online_exam_id FROM online_exam_table 
  WHERE online_exam_code = '$exam_code'
  ";

  $result = $this->query_result();

  foreach($result as $row)
  {
   return $row['online_exam_id'];
  }
 }
 
 function Upload_file()
 {
  if(!empty($this->filedata['name']))
  {
   $extension = pathinfo($this->filedata['name'], PATHINFO_EXTENSION);

   $new_name = uniqid() . '.' . $extension;

   $_source_path = $this->filedata['tmp_name'];

   $target_path = 'upload/' . $new_name;

   move_uploaded_file($_source_path, $target_path);

   return $new_name;
  }
 }
 
 function user_session_private()
 {
  if(!isset($_SESSION['user_id']))
  {
   $this->redirect('login.php');
  }
 }

 function user_session_public()
 {
  if(isset($_SESSION['user_id']))
  {
   $this->redirect('index.php');
  }
 }
}

?>


master/ajax_action.php


In this PHP file you will find the PHP script of all operations that you performed on the master side. You can find it here. This file receives Ajax's request to perform another operation.

This file contains the Examination.php class and the PHPMailer class library. There are various operations related to the database that are performed here.


  • In this file, you first received the Ajax request from the administrator registration page to check whether the administrator email in question is already registered in the MySQL database or not.
  • After verifying each administrator's email address, this page also received a second Ajax request from the administrator registration page to complete the administrator registration process. Once the registration information is entered, it will be sent A dynamic administrator email confirmation email that will be sent to the administrator email address for the email confirmation process.
  • After registration was completed and the administrator attempted to log on to the system, the administrator credentials were checked here by requesting Ajax.
  • This PHP script also receives an Ajax request from the Exam.php file. From this file you will first receive the Ajax request to retrieve data from the MySQL table and return the response in JSON format.
  • On this page, Ajax is asked to insert new data from the online exam program into the MySQL table.
  • Once the exam details are saved in this system. Now the administrator wants to change the exam details online so that the individual exam details are retrieved from this page by sending an Ajax request.
  • If details of certain tests were displayed in bootstrap mode and the administrator made the necessary changes and clicked the "Edit" button, Ajax's request to edit the data is received and here the test data is updated with Ajax with PHP script.
  • Examination details are also removed or deleted from this file. Then the operation to remove the check is performed here.

master/ajax_action.php


<?php

//ajax_action.php

include('Examination.php');

require_once('../class/class.phpmailer.php');

$exam = new Examination;

$current_datetime = date("Y-m-d") . ' ' . date("H:i:s", STRTOTIME(date('h:i:sa')));

if(isset($_POST['page']))
{
 if($_POST['page'] == 'register')
 {
  if($_POST['action'] == 'check_email')
  {
   $exam->query = "
   SELECT * FROM admin_table 
   WHERE admin_email_address = '".trim($_POST["email"])."'
   ";

   $total_row = $exam->total_row();

   if($total_row == 0)
   {
    $output = array(
     'success' => true
    );

    echo json_encode($output);
   }
  }

  if($_POST['action'] == 'register')
  {
   $admin_verification_code = md5(rand());

   $receiver_email = $_POST['admin_email_address'];

   $exam->data = array(
    ':admin_email_address'  => $receiver_email,
    ':admin_password'   => password_hash($_POST['admin_password'], PASSWORD_DEFAULT),
    ':admin_verfication_code' => $admin_verification_code,
    ':admin_type'    => 'sub_master', 
    ':admin_created_on'   => $current_datetime
   );

   $exam->query = "
   INSERT INTO admin_table 
   (admin_email_address, admin_password, admin_verfication_code, admin_type, admin_created_on) 
   VALUES 
   (:admin_email_address, :admin_password, :admin_verfication_code, :admin_type, :admin_created_on)
   ";

   $exam->execute_query();

   $subject = 'Online Examination Registration Verification';

   $body = '
   <p>Thank you for registering.</p>
   <p>This is a verification eMail, please click the link to verify your eMail address by clicking this <a href="'.$exam->home_page.'verify_email.php?type=master&code='.$admin_verification_code.'" target="_blank"><b>link</b></a>.</p>
   <p>In case if you have any difficulty please eMail us.</p>
   <p>Thank you,</p>
   <p>Online Examination System</p>
   ';

   $exam->send_email($receiver_email, $subject, $body);

   $output = array(
    'success' => true
   );

   echo json_encode($output);
  }
 }

 if($_POST['page'] == 'login')
 {
  if($_POST['action'] == 'login')
  {
   $exam->data = array(
    ':admin_email_address' => $_POST['admin_email_address']
   );

   $exam->query = "
   SELECT * FROM admin_table 
   WHERE admin_email_address = :admin_email_address
   ";

   $total_row = $exam->total_row();

   if($total_row > 0)
   {
    $result = $exam->query_result();

    foreach($result as $row)
    {
     if($row['email_verified'] == 'yes')
     {
      if(password_verify($_POST['admin_password'], $row['admin_password']))
      {
       $_SESSION['admin_id'] = $row['admin_id'];
       $output = array(
        'success' => true
       );
      }
      else
      {
       $output = array(
        'error' => 'Wrong Password'
       );
      }
     }
     else
     {
      $output = array(
       'error'  => 'Your Email is not verify'
      );
     }
    }
   }
   else
   {
    $output = array(
     'error'  => 'Wrong Email Address'
    );
   }
   echo json_encode($output);
  }
 }

 if($_POST['page'] == 'exam')
 {
  if($_POST['action'] == 'fetch')
  {
   $output = array();

   $exam->query = "
   SELECT * FROM online_exam_table 
   WHERE admin_id = '".$_SESSION["admin_id"]."' 
   AND (
   ";

   if(isset($_POST['search']['value']))
   {
    $exam->query .= 'online_exam_title LIKE "%'.$_POST["search"]["value"].'%" ';

    $exam->query .= 'OR online_exam_datetime LIKE "%'.$_POST["search"]["value"].'%" ';

    $exam->query .= 'OR online_exam_duration LIKE "%'.$_POST["search"]["value"].'%" ';

    $exam->query .= 'OR total_question LIKE "%'.$_POST["search"]["value"].'%" ';

    $exam->query .= 'OR marks_per_right_answer LIKE "%'.$_POST["search"]["value"].'%" ';

    $exam->query .= 'OR marks_per_wrong_answer LIKE "%'.$_POST["search"]["value"].'%" ';

    $exam->query .= 'OR online_exam_status LIKE "%'.$_POST["search"]["value"].'%" ';
   }

   $exam->query .= ')';

   if(isset($_POST['order']))
   {
    $exam->query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
   }
   else
   {
    $exam->query .= 'ORDER BY online_exam_id DESC ';
   }

   $extra_query = '';

   if($_POST['length'] != -1)
   {
    $extra_query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
   }

   $filtered_rows = $exam->total_row();

   $exam->query .= $extra_query;

   $result = $exam->query_result();

   $exam->query = "
   SELECT * FROM online_exam_table 
   WHERE admin_id = '".$_SESSION["admin_id"]."'
   ";

   $total_rows = $exam->total_row();

   $data = array();

   foreach($result as $row)
   {
    $sub_array = array();
    $sub_array[] = html_entity_decode($row['online_exam_title']);

    $sub_array[] = $row['online_exam_datetime'];

    $sub_array[] = $row['online_exam_duration'] . ' Minute';

    $sub_array[] = $row['total_question'] . ' Question';

    $sub_array[] = $row['marks_per_right_answer'] . ' Mark';


    $sub_array[] = '-' . $row['marks_per_wrong_answer'] . ' Mark';

    $status = '';

    $edit_button = '';
    $delete_button = '';
    $question_button = '';

    if($row['online_exam_status'] == 'Pending')
    {
     $status = '<span class="badge badge-warning">Pending</span>';
    }

    if($row['online_exam_status'] == 'Created')
    {
     $status = '<span class="badge badge-success">Created</span>';
    }

    if($row['online_exam_status'] == 'Started')
    {
     $status = '<span class="badge badge-primary">Started</span>';
    }

    if($row['online_exam_status'] == 'Completed')
    {
     $status = '<span class="badge badge-dark">Completed</span>';
    }

    if($exam->Is_exam_is_not_started($row["online_exam_id"]))
    {
     $edit_button = '
     <button type="button" name="edit" class="btn btn-primary btn-sm edit" id="'.$row['online_exam_id'].'">Edit</button>
     ';

     $delete_button = '<button type="button" name="delete" class="btn btn-danger btn-sm delete" id="'.$row['online_exam_id'].'">Delete</button>';

    }

    if($exam->Is_allowed_add_question($row['online_exam_id']))
    {
     $question_button = '
     <button type="button" name="add_question" class="btn btn-info btn-sm add_question" id="'.$row['online_exam_id'].'">Add Question</button>
     ';
    }
    else
    {
     $question_button = '
     <a href="question.php?code='.$row['online_exam_code'].'" class="btn btn-warning btn-sm">View Question</a>
     ';
    }

    $sub_array[] = $status;

    $sub_array[] = $question_button;

    $sub_array[] = $edit_button . ' ' . $delete_button;

    $data[] = $sub_array;
   }

   $output = array(
    "draw"    => intval($_POST["draw"]),
    "recordsTotal"  => $total_rows,
    "recordsFiltered" => $filtered_rows,
    "data"    => $data
   );

   echo json_encode($output);
  }

  if($_POST['action'] == 'Add')
  {
   $exam->data = array(
    ':admin_id'    => $_SESSION['admin_id'],
    ':online_exam_title' => $exam->clean_data($_POST['online_exam_title']),
    ':online_exam_datetime' => $_POST['online_exam_datetime'] . ':00',
    ':online_exam_duration' => $_POST['online_exam_duration'],
    ':total_question'  => $_POST['total_question'],
    ':marks_per_right_answer'=> $_POST['marks_per_right_answer'],
    ':marks_per_wrong_answer'=> $_POST['marks_per_wrong_answer'],
    ':online_exam_created_on'=> $current_datetime,
    ':online_exam_status' => 'Pending',
    ':online_exam_code'  => md5(rand())
   );

   $exam->query = "
   INSERT INTO online_exam_table 
   (admin_id, online_exam_title, online_exam_datetime, online_exam_duration, total_question, marks_per_right_answer, marks_per_wrong_answer, online_exam_created_on, online_exam_status, online_exam_code) 
   VALUES (:admin_id, :online_exam_title, :online_exam_datetime, :online_exam_duration, :total_question, :marks_per_right_answer, :marks_per_wrong_answer, :online_exam_created_on, :online_exam_status, :online_exam_code)
   ";

   $exam->execute_query();

   $output = array(
    'success' => 'New Exam Details Added'
   );

   echo json_encode($output);
  }

  if($_POST['action'] == 'edit_fetch')
  {
   $exam->query = "
   SELECT * FROM online_exam_table 
   WHERE online_exam_id = '".$_POST["exam_id"]."'
   ";

   $result = $exam->query_result();

   foreach($result as $row)
   {
    $output['online_exam_title'] = $row['online_exam_title'];

    $output['online_exam_datetime'] = $row['online_exam_datetime'];

    $output['online_exam_duration'] = $row['online_exam_duration'];

    $output['total_question'] = $row['total_question'];

    $output['marks_per_right_answer'] = $row['marks_per_right_answer'];

    $output['marks_per_wrong_answer'] = $row['marks_per_wrong_answer'];
   }

   echo json_encode($output);
  }

  if($_POST['action'] == 'Edit')
  {
   $exam->data = array(
    ':online_exam_title' => $_POST['online_exam_title'],
    ':online_exam_datetime' => $_POST['online_exam_datetime'] . ':00',
    ':online_exam_duration' => $_POST['online_exam_duration'],
    ':total_question'  => $_POST['total_question'],
    ':marks_per_right_answer'=> $_POST['marks_per_right_answer'],
    ':marks_per_wrong_answer'=> $_POST['marks_per_wrong_answer'],
    ':online_exam_id'  => $_POST['online_exam_id']
   );

   $exam->query = "
   UPDATE online_exam_table 
   SET online_exam_title = :online_exam_title, online_exam_datetime = :online_exam_datetime, online_exam_duration = :online_exam_duration, total_question = :total_question, marks_per_right_answer = :marks_per_right_answer, marks_per_wrong_answer = :marks_per_wrong_answer  
   WHERE online_exam_id = :online_exam_id
   ";

   $exam->execute_query($exam->data);

   $output = array(
    'success' => 'Exam Details has been changed'
   );

   echo json_encode($output);
  }
  if($_POST['action'] == 'delete')
  {
   $exam->data = array(
    ':online_exam_id' => $_POST['exam_id']
   );

   $exam->query = "
   DELETE FROM online_exam_table 
   WHERE online_exam_id = :online_exam_id
   ";

   $exam->execute_query();

   $output = array(
    'success' => 'Exam Details has been removed'
   );

   echo json_encode($output);
  }
 }

 if($_POST['page'] == 'question')
 {
  if($_POST['action'] == 'Add')
  {
   $exam->data = array(
    ':online_exam_id'  => $_POST['online_exam_id'],
    ':question_title'  => $exam->clean_data($_POST['question_title']),
    ':answer_option'  => $_POST['answer_option']
   );

   $exam->query = "
   INSERT INTO question_table 
   (online_exam_id, question_title, answer_option) 
   VALUES (:online_exam_id, :question_title, :answer_option)
   ";

   $question_id = $exam->execute_question_with_last_id($exam->data);

   for($count = 1; $count <= 4; $count++)
   {
    $exam->data = array(
     ':question_id'  => $question_id,
     ':option_number' => $count,
     ':option_title'  => $exam->clean_data($_POST['option_title_' . $count])
    );

    $exam->query = "
    INSERT INTO option_table 
    (question_id, option_number, option_title) 
    VALUES (:question_id, :option_number, :option_title)
    ";

    $exam->execute_query($exam->data);
   }

   $output = array(
    'success'  => 'Question Added'
   );

   echo json_encode($output);
  }

  if($_POST['action'] == 'fetch')
  {
   $output = array();
   $exam_id = '';
   if(isset($_POST['code']))
   {
    $exam_id = $exam->Get_exam_id($_POST['code']);
   }
   $exam->query = "
   SELECT * FROM question_table 
   WHERE online_exam_id = '".$exam_id."' 
   AND (
   ";

   if(isset($_POST['search']['value']))
   {
    $exam->query .= 'question_title LIKE "%'.$_POST["search"]["value"].'%" ';
   }

   $exam->query .= ')';

   if(isset($_POST["order"]))
   {
    $exam->query .= '
    ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' 
    ';
   }
   else
   {
    $exam->query .= 'ORDER BY question_id ASC ';
   }

   $extra_query = '';

   if($_POST['length'] != -1)
   {
    $extra_query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
   }

   $filtered_rows = $exam->total_row();

   $exam->query .= $extra_query;

   $result = $exam->query_result();

   $exam->query = "
   SELECT * FROM question_table 
   WHERE online_exam_id = '".$exam_id."'
   ";

   $total_rows = $exam->total_row();

   $data = array();

   foreach($result as $row)
   {
    $sub_array = array();

    $sub_array[] = $row['question_title'];

    $sub_array[] = 'Option ' . $row['answer_option'];

    $edit_button = '';
    $delete_button = '';

    if($exam->Is_exam_is_not_started($exam_id))
    {
     $edit_button = '<button type="button" name="edit" class="btn btn-primary btn-sm edit" id="'.$row['question_id'].'">Edit</button>';

     $delete_button = '<button type="button" name="delete" class="btn btn-danger btn-sm delete" id="'.$row['question_id'].'">Delete</button>';
    }

    $sub_array[] = $edit_button . ' ' . $delete_button;

    $data[] = $sub_array;
   }

   $output = array(
    "draw"  => intval($_POST["draw"]),
    "recordsTotal" => $total_rows,
    "recordsFiltered" => $filtered_rows,
    "data"  => $data
   );

   echo json_encode($output);
  }

  if($_POST['action'] == 'edit_fetch')
  {
   $exam->query = "
   SELECT * FROM question_table 
   WHERE question_id = '".$_POST["question_id"]."'
   ";

   $result = $exam->query_result();

   foreach($result as $row)
   {
    $output['question_title'] = html_entity_decode($row['question_title']);

    $output['answer_option'] = $row['answer_option'];

    for($count = 1; $count <= 4; $count++)
    {
     $exam->query = "
     SELECT option_title FROM option_table 
     WHERE question_id = '".$_POST["question_id"]."' 
     AND option_number = '".$count."'
     ";

     $sub_result = $exam->query_result();

     foreach($sub_result as $sub_row)
     {
      $output["option_title_" . $count] = html_entity_decode($sub_row["option_title"]);
     }
    }
   }

   echo json_encode($output);
  }

  if($_POST['action'] == 'Edit')
  {
   $exam->data = array(
    ':question_title'  => $_POST['question_title'],
    ':answer_option'  => $_POST['answer_option'],
    ':question_id'   => $_POST['question_id']
   );

   $exam->query = "
   UPDATE question_table 
   SET question_title = :question_title, answer_option = :answer_option 
   WHERE question_id = :question_id
   ";

   $exam->execute_query();

   for($count = 1; $count <= 4; $count++)
   {
    $exam->data = array(
     ':question_id'  => $_POST['question_id'],
     ':option_number' => $count,
     ':option_title'  => $_POST['option_title_' . $count]
    );

    $exam->query = "
    UPDATE option_table 
    SET option_title = :option_title 
    WHERE question_id = :question_id 
    AND option_number = :option_number
    ";
    $exam->execute_query();
   }

   $output = array(
    'success' => 'Question Edit'
   );

   echo json_encode($output);
  }
  
  if($_POST['action'] == 'delete')
  {
   $exam->data = array(
    ':question_id' => $_POST["question_id"]
   );

   $exam->query = "
   DELETE FROM question_table 
   WHERE question_id = :question_id
   ";

   $exam->execute_query();

   $exam->query = "
   DELETE FROM option_table 
   WHERE question_id = :question_id
   ";

   $exam->execute_query();

   $output = array(
    'success'  => 'Question Details has been removed'
   );

   echo json_encode($output);
  }
 }
}

?>