Tuesday, 18 June 2019

How to use Date Range Filter For Export Data to CSV File in PHP



This is one more post on Exporting of Mysql data. In this post we will learn How to export Mysql data to CSV file by using PHP script. But here we add on feature like date range, that means here we will discuss how to export only those mysql data which has come between two define date to CSV file format by using PHP script. So, here you can learn How to export mysql data for specific date into Excel sheet or CSV file format via PHP.

If you have already learn How to Export Data to CSV file or Excel Sheet using PHP script. But suppose we do not want to export whole Mysql data into CSV file or Excel spread sheet but we want to Export those Data to CSV file with PHP which has come between select date range. So, at that time this turial will help you to learn How to export mysql data to CSV file or Excel sheet by using date range filter with PHP script. This is feature will add usability of your web application and use can freely to export those data which he want to export and he do not export whole unwanted data. This feature will reduce your website bandwidth and reduce load on your mysql database because only required or filtered data only has been exported into CSV file or Excel sheet.

In this post we want to Export date range filter data in CSV file using PHP then in PHP there are many PHP build in file system function is available for export data to CSV file. Here we have use some PHP function like fopen(), fputcsv(), fclose() for Export data to CSV file. Here fopen() function will open file in PHP stream. After this fputcsv() function will write data in open file and fclose() function will close open file. So, this basic PHP function has been used for export data to CSV file in PHP. But here we have not only export mysql data to csv file but also here we have export filtered data exported into csv file. So for filter data here we have use date range that means define two date and only export only those data which has come between this two define data. This we can done in mysql query which you can find below. For date range selection here we have use bootstrap date picker plugin. So, this simple tutorial on How to use Date Range Filter with Export Data to CSV File in PHP. Below you can find complete source code also.







Source Code


Database (tbl_order)



DROP TABLE IF EXISTS `tbl_order`;

CREATE TABLE `tbl_order` (
  `order_id` int(11) NOT NULL AUTO_INCREMENT,
  `order_customer_name` varchar(255) NOT NULL,
  `order_item` varchar(255) NOT NULL,
  `order_value` double(12,2) NOT NULL,
  `order_date` date NOT NULL,
  PRIMARY KEY (`order_id`)
) ENGINE=MyISAM AUTO_INCREMENT=21 DEFAULT CHARSET=latin1;

/*Data for the table `tbl_order` */

insert  into `tbl_order`(`order_id`,`order_customer_name`,`order_item`,`order_value`,`order_date`) values 
(1,'David E. Gary','Shuttering Plywood',1500.00,'2019-06-14'),
(2,'Eddie M. Douglas','Aluminium Heavy Windows',2000.00,'2019-06-08'),
(3,'Oscar D. Scoggins','Plaster Of Paris',150.00,'2019-05-29'),
(4,'Clara C. Kulik','Spin Driller Machine',350.00,'2019-05-30'),
(5,'Christopher M. Victory','Shopping Trolley',100.00,'2019-06-01'),
(6,'Jessica G. Fischer','CCTV Camera',800.00,'2019-06-02'),
(7,'Roger R. White','Truck Tires',2000.00,'2019-05-28'),
(8,'Susan C. Richardson','Glass Block',200.00,'2019-06-04'),
(9,'David C. Jury','Casing Pipes',500.00,'2019-05-27'),
(10,'Lori C. Skinner','Glass PVC Rubber',1800.00,'2019-05-30'),
(11,'Shawn S. Derosa','Sony HTXT1 2.1-Channel TV',180.00,'2019-06-03'),
(12,'Karen A. McGee','Over-the-Ear Stereo Headphones ',25.00,'2019-06-01'),
(13,'Kristine B. McGraw','Tristar 10\" Round Copper Chef Pan with Glass Lid',20.00,'2019-05-30'),
(14,'Gary M. Porter','ROBO 3D R1 Plus 3D Printer',600.00,'2019-06-02'),
(15,'Sarah D. Hunter','Westinghouse Select Kitchen Appliances',35.00,'2019-05-29'),
(16,'Diane J. Thomas','SanDisk Ultra 32GB microSDHC',12.00,'2019-06-05'),
(17,'Helena J. Quillen','TaoTronics Dimmable Outdoor String Lights',16.00,'2019-06-04'),
(18,'Arlette G. Nathan','TaoTronics Bluetooth in-Ear Headphones',25.00,'2019-06-03'),
(19,'Ronald S. Vallejo','Scotchgard Fabric Protector, 10-Ounce, 2-Pack',20.00,'2019-06-03'),
(20,'Felicia L. Sorensen','Anker 24W Dual USB Wall Charger with Foldable Plug',12.00,'2019-06-04');


index.php



<?php

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

$start_date_error = '';
$end_date_error = '';

if(isset($_POST["export"]))
{
 if(empty($_POST["start_date"]))
 {
  $start_date_error = '<label class="text-danger">Start Date is required</label>';
 }
 else if(empty($_POST["end_date"]))
 {
  $end_date_error = '<label class="text-danger">End Date is required</label>';
 }
 else
 {
  $file_name = 'Order Data.csv';
  header("Content-Description: File Transfer");
  header("Content-Disposition: attachment; filename=$file_name");
  header("Content-Type: application/csv;");

  $file = fopen('php://output', 'w');

  $header = array("Order ID", "Customer Name", "Item Name", "Order Value", "Order Date");

  fputcsv($file, $header);

  $query = "
  SELECT * FROM tbl_order 
  WHERE order_date >= '".$_POST["start_date"]."' 
  AND order_date <= '".$_POST["end_date"]."' 
  ORDER BY order_date DESC
  ";
  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $data = array();
   $data[] = $row["order_id"];
   $data[] = $row["order_customer_name"];
   $data[] = $row["order_item"];
   $data[] = $row["order_value"];
   $data[] = $row["order_date"];
   fputcsv($file, $data);
  }
  fclose($file);
  exit;
 }
}

$query = "
SELECT * FROM tbl_order 
ORDER BY order_date DESC;
";

$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();

?>

<html>
 <head>
  <title>Daterange Mysql Data Export to CSV in PHP</title>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
 </head>
 <body>
  <div class="container box">
   <h1 align="center">Daterange Mysql Data Export to CSV in PHP</h1>
   <br />
   <div class="table-responsive">
    <br />
    <div class="row">
     <form method="post">
      <div class="input-daterange">
       <div class="col-md-4">
        <input type="text" name="start_date" class="form-control" readonly />
        <?php echo $start_date_error; ?>
       </div>
       <div class="col-md-4">
        <input type="text" name="end_date" class="form-control" readonly />
        <?php echo $end_date_error; ?>
       </div>
      </div>
      <div class="col-md-2">
       <input type="submit" name="export" value="Export" class="btn btn-info" />
      </div>
     </form>
    </div>
    <br />
    <table class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>Order ID</th>
       <th>Customer Name</th>
       <th>Item</th>
       <th>Value</th>
       <th>Order Date</th>
      </tr>
     </thead>
     <tbody>
      <?php
      foreach($result as $row)
      {
       echo '
       <tr>
        <td>'.$row["order_id"].'</td>
        <td>'.$row["order_customer_name"].'</td>
        <td>'.$row["order_item"].'</td>
        <td>$'.$row["order_value"].'</td>
        <td>'.$row["order_date"].'</td>
       </tr>
       ';
      }
      ?>
     </tbody>
    </table>
    <br />
    <br />
   </div>
  </div>
 </body>
</html>

<script>

$(document).ready(function(){
 $('.input-daterange').datepicker({
  todayBtn:'linked',
  format: "yyyy-mm-dd",
  autoclose: true
 });
});

</script>

Friday, 14 June 2019

How to Insert Multiple Data into Mysql in PHP using TextArea Field



If you want to learn how can we insert multiple records into Mysql Database by using Single TextArea field with PHP script. Or in second word How to Insert Multiple Data from Textarea field to Mysql table in PHP script. We have already seen single insert data into database in PHP by using different HTML field, but we have first time discuss how to insert multiple data from textarea into database in PHP. In this tutorial, you can learn two things from this single post. One is you can learn How to insert multiple rows from TextArea to Mysql using PHP and second one is how can we insert multiple data into Mysql table in PHP PDO.

For learn this topic here we have take example of inserting of multiple email addresses into mysql database by using textarea field with PHP script. There are many different event has occur in which we want to insert mass email into database. So, at that time insert email one by one will take lots of time for inserting data into database. But if you have use textarea field then you can insert multiple email address at the same time.

Now question arise how to insert multiple data into mysql by using textarea field in PHP. This will be done by if you have enter multiple email address in one email in one line and past into textarea field. Below PHP script will convert line by line email into array. After this below PHP script will make insert data query for insert multiple data by executing single mysql insert query. This query will insert multiple data in single query execution. In this script we have use to main PHP function like explode() and array_unique(). This explode() function will make textarea field value into array by using "\r\n" string delimiter and array_unique() function will remove duplicate email from array. So, this script will help you to learn PHP insert multiple records into Mysql using TextArea field. Below you can find complete source code and online demo also.






Source Code


Database



CREATE TABLE `tbl_email_list` (
  `email_list_id` int(11) NOT NULL AUTO_INCREMENT,
  `email_address` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`email_list_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;




index.php



<?php

//index.php

$error = '';
$output = '';

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

if(isset($_POST["add"]))
{
    if(empty($_POST["email_address"]))
    {
        $error = '<label class="text-danger">Email Address List is required</label>';
    }
    else
    {
        $array = explode("\r\n", $_POST["email_address"]);

        $email_array = array_unique($array);

        $query = "
        INSERT INTO tbl_email_list 
        (email_address) 
        VALUES ('".implode("'),('", $email_array)."')
        ";

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

        $statement->execute();

        $error = '<label class="text-success">Data Inserted Successfully</label>';
    }
}

$query = "
SELECT * FROM tbl_email_list 
ORDER BY email_list_id DESC
";

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

$statement->execute();

if($statement->rowCount() > 0)
{
    $result = $statement->fetchAll();
    foreach($result as $row)
    {
        $output .= '
        <tr>
            <td>'.$row["email_address"].'</td>
        </tr>
        ';
    }
}
else
{
    $output .= '
        <tr>
            <td>No Data Found</td>
        </tr>
    ';
}

?>

<html>
    <head>
        <title>Insert multiple data to mysql using single textarea in PHP</title>  
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    </head>  
    <body>
        <div class="container">    
            <div class="row content">
                <div class="col-sm-2">
                    &nbsp;
                </div>
                <div class="col-sm-8 text-left">
                    <br />
                    <h3 align="center">Insert Multiple Data to Mysql using Textarea in PHP</h3>
                    <br />
                    <div align="center"><?php echo $error; ?></div>
                    <form method="post">
                        <div class="row">
                            <label class="col-md-3 text-right">Enter Email List</label>
                            <div class="col-md-9">
                                 <textarea name="email_address" class="form-control" rows="10"></textarea>
                            </div>
                        </div>
                        <br />
                        <div align="center">
                            <input type="submit" name="add" class="btn btn-primary" value="Add" />
                        </div>
                    </form>
                    <br />
                    <h3 align="center">Email List</h3>
                    <br />
                    <table class="table table-striped table-bordered">
                        <tr>
                            <td>Email Address</td>
                        </tr>
                        <?php
                        echo $output;
                        ?>
                    </table>
                </div>
                <div class="col-sm-2">
                    &nbsp;
                </div>
            </div>
        </div>
    </body>  
</html>

Tuesday, 11 June 2019

How to Import Export CSV File Data in Laravel 5.8



Do you know Import or Export CSV or Excel sheet data from Mysql Database is a primary needs of any admin level project. For this here we have make simple tutorial, in which we have step by step describe how to import CSV or Excel sheet data and Export CSV File or Excel sheet data in Laravel 5.8 application by using maatwebsite/excel version 3 package. There are many changes has been done in maatwebsite version 3 package. So, you have to need to know how to Export or Import of CSV or Excel file data in Laravel 5.8 with Mysql database. This updated package is now very simple and easy way to use with Laravel latest version like 5.7 and 5.8 for import excel CSV file data from Mysql database.

Suppose We have to some time export or import thousand of records import or export from our database. Then Maatwebsite has been offer functionality for importing and exporting of large records in CSV file or Excel sheet. For learn this feature here we will make import data in CSV file and import into mysql in laravel 5.8 application. For this task here we will use maatwebsite/excel package for importing and exporting data task with laravel 5.8 framework. Because maatwebsite/excel package has provide very easy method for import and export data using database model. Below you can find step by step process for how to use maatwebsite/excel version for import and export csv file data in Laravel 5.8 application.



How to Import Export CSV File Data in Laravel 5.8


Content


  • Install Laravel 5.8 framework

  • Add Fake Records in Mysql Database

  • Install Maatwebsite Package

  • Create Import Class

  • Create Export Class

  • Create Controller

  • Create Blade View File

  • Add route


Install Laravel 5.8 framework


First We need to download Laravel 5.8 version, and install into our computer. For this we have to go command prompt, in which we have to already run composer command and write following command. It will download Laravel 5.8 version in define folder.


composer create-project --prefer-dist laravel/laravel csv_file


After installing Laravel 5.8 framwork, after this we need to make database connection. For this we have to open .env file and under this file we have to define Mysql database configuration details which you can see below.


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


After makiing database configuration, now in next step we will see how to make table from Laravel 5.8 application.

Add Fake Records in Mysql Database


For add fake record into Mysql database. First we want to make table in Mysql database from this Laravel 5.8 application. Here we will use user default model for migrate data from this Laravel 5.8 application. If you have download fresh Laravel 5.8 framework, then you can find User default model in app/User.php. And for migrate data, you have to go command prompt and write following command.


php artisan migrate


This command will migrate default data from database/migrations folder and it will make user table in define Mysql database. Now for add fake records, we have to write following command in command prompt.


php artisan tinker

factory(App\User::class, 20)->create();


This command will add 20 fake records in User table, so we can perform import export data operation with CSV file.

Install Maatwebsite Package


Now for import and export data to csv file, we need to download and install Maatwebsite Version 3.0 package, for this we have go to command prompt and write following command.


composer require maatwebsite/excel


This command will download maatwebsite package in Laravel 5.8 application. Now we want to add into Laravel 5.8 application. For this we have open config/app.php and following service provider and aliase.

config/app.php

'providers' => [

 ....

 Maatwebsite\Excel\ExcelServiceProvider::class,

],

'aliases' => [

 ....

 'Excel' => Maatwebsite\Excel\Facades\Excel::class,

],


So, this way we can add maatwebsite/excel package in Laravel 5.8 application.




Create Import Class


Now we want to create import class for import data using maatwebsite 3.0 package in Laravel 5.8 frameworl. For this we have to write following command in command prompt.


php artisan make:import CsvImport --model=User


This command will make CsvImport.php import class under Import. We have to open this class and under this we to define table column which data we want to get from CSV file. Below you can find complete source code of Import Class for import data from CSV file by using Maatwebsite/excel 3.0 package in Laravel 5.8.

Imports/CsvImport.php

<?php

namespace App\Imports;

use App\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class CsvImport implements ToModel, WithHeadingRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new User([
            'name'      =>  $row["name"],
            'email'     =>  $row["email"],
            'password'  =>  \Hash::make($row['password']),
        ]);
    }
}


Create Export Class


After this for export mysql data into CSV file or excel sheet, we need to create Export class of maatwebsite using Laravel model. For this we have to write following command in command prompt.


php artisan make:export CsvExport --model=User


This command will make CsvExport.php class under Exports folder. You can find source code of this class below. We need to add this class into controller header for export data into CSV or Excel file.

Exports/CsvExport.php

<?php

namespace App\Exports;

use App\User;
use Maatwebsite\Excel\Concerns\FromCollection;

class CsvExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return User::all();
    }
}


Create Controller


Now we have to create controller for handle http request for import and export data. For this we have to write following command in command prompt.


php artisan make:controller CsvFile


This command will create controller under app/Http/Controllers/CsvFile.php file. In this file first we need to add import class, export class, maatwebsite and User model class. In this controller we have make following method.

index() - This method has load all data of user data with pagination feature.
csv_export() - This method has been received data export to csv file request. This method will export all User table data into CSV file format using CsvExport class and CSV file download in computer.
csv_import() - This method has been used for import csv file data into Mysql database. This method has import data from csv file by using CsvImport class.

Create Blade View File


For display output in browser, we have to create blade file for display Laravel 5.8 application output on browser. You can find below two blade file has been used for display output on web page.

resources/views/csv_file.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - Import Export Data in CSV File</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 5.8 - Import Export Data in CSV File</h3>
     <br />
     <div class="panel panel-default">
          <div class="panel-heading">
           <h3 class="panel-title">Laravel 5.8 - Import Export Data in CSV File</h3>
          </div>
          <div class="panel-body">
           <form action="{{ route('import') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <input type="file" name="file" accept=".csv">
                  <br>
                  <button class="btn btn-success">Import User Data</button>
                  <a class="btn btn-warning" href="{{ route('export') }}">Export User Data</a>
           </form>
              @yield('csv_data')
          </div>
      </div>
  </div>
 </body>
</html>


resources/views/csv_file_pagination.blade.php

@extends('csv_file')

@section('csv_data')

<table class="table table-bordered table-striped">
 <thead>
  <tr>
   <th>Name</th>
   <th>Email Address</th>
  </tr>
 </thead>
 <tbody>
 @foreach($data as $row)
  <tr>
   <td>{{ $row->name }}</td>
   <td>{{ $row->email }}</td>
  </tr>
 @endforeach
 </tbody>
</table>

{!! $data->links() !!}

@endsection


Add route


Lastly we need to add route for import and export operation. For this we have to open routes/web.php file. In this file you can define below route for import and export method.


Route::get('csv_file', 'CsvFile@index');

Route::get('csv_file/export', 'CsvFile@csv_export')->name('export');

Route::post('csv_file/import', 'CsvFile@csv_import')->name('import');


Now we are ready for import and export data into CSV file in Laravel 5.8 by using maatwebsite 3.0 version. For this first we want to start Laravel 5.8 server, for this we have to write following command in command prompt.


php artisan serve


This command will start Laravel server and give you base url of Laravel application. For test import and export data operation we have to write following url in browser.


http://localhost:8000/csv_file


Now you can check your Laravel 5.8 import export data into CSV file. We hope it will help you to learn Laravel 5.8 with maatwebsite package.

Friday, 17 May 2019

Online Student Attendance System in PHP Mysql







Do you know Online Attendance Management System is an advance tool, which help us to manage and maintain the records of student attendance. This type of tool mainly a one type of software that keep observe attendance details.

Here this is online attendance system, that means this system has very useful technique, because this system we can access from anywhere from any device, because this system has been develop by responsive web technology.

This is very simple and user friendly attendance management system for teacher, who want to digitize their student attendance record online. Digitize means convert paper work process into digital form, and store all data online, So he can view all details in single click.

For make this student attendance system in PHP Mysql, we have use all opensource technology like PHP, Mysql, jQery, Ajax, Bootstrap 4, jQuery Datatable plugin, Bootstrap Datepicker plugin. If you are looiking for your College project, then you can use this system in your education project also.

So, are you ready for learn how to make simple Student Attendance system in PHP and Mysql. So you have come on right place with right time, because here we have make tutorial on attendance management system by using latest web technology.

Features of Attendance Management System


The main feature of this Student Attendance system is that store student daily attendance record, and make PDF report from attendance data. This is very simple system, there are main two user, one is admin and other one is teacher. Admin has all rights for view or access system data, while teacher has rights to view only his or her grade student data. In this system Admin and teacher password has been store in encrypted form.

User of this System


  • Admin
  • Teacher

Admin Activity


  • Admin can Add Update Delete Grade Master Data
  • Admin has rights to add new teacher account, edit teacher details, and remove teacher account
  • Admin can assign grade to teacher, so teacher can view his or her student and take attendace of that student only.
  • Admin can Add new student, edit existing student and delete student data. Student grade also assign by admin only.
  • Admin can view all student attendance records of any grade.
  • Admin can make pdf report of any student attendance record
  • Admin can view all student overall attendance details in percentage form.

Teacher Activity


  • Teacher can update his or her profile details like change password, change profile picture etc
  • Teacher can view his or her grade student list.
  • Teacher can take attendance of his or her grade student.
  • Teacher can view his or her grade student attendance details
  • Teacher can generate PDF report of Attendance records.
  • Teacher can view overall attendance percentage of all student of his or her grade.

We have following Web Technology has been used for this attendance management system.



Database Structure




Directory Stucture

Below you can find directory structure of this attendance management system project in PHP.








admin/database_connection.php



<?php

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

$base_url = "http://localhost/tutorial/student-attendance-system-in-php-using-ajax/";

function get_total_records($connect, $table_name)
{
 $query = "
 SELECT * FROM $table_name
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 return $statement->rowCount();
}

function load_grade_list($connect)
{
 $query = "
 SELECT * FROM tbl_grade ORDER BY grade_name ASC
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '';
 foreach($result as $row)
 {
  $output .= '<option value="'.$row["grade_id"].'">'.$row["grade_name"].'</option>';
 }
 return $output;
}

function get_attendance_percentage($connect, $student_id)
{
 $query = "
 SELECT 
  ROUND((SELECT COUNT(*) FROM tbl_attendance 
  WHERE attendance_status = 'Present' 
  AND student_id = '".$student_id."') 
 * 100 / COUNT(*)) AS percentage FROM tbl_attendance 
 WHERE student_id = '".$student_id."'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  if($row["percentage"] > 0)
  {
   return $row["percentage"] . '%';
  }
  else
  {
   return 'NA';
  }
 }
}


?>


Admin Login


admin/login.php



<?php

//login.php

include('database_connection.php');

session_start();

if(isset($_SESSION["admin_id"]))
{
  header('location:index.php');
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Student Attendance System in PHP using Ajax</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://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>
</head>
<body>

<div class="jumbotron text-center" style="margin-bottom:0">
  <h1>Student Attendance System</h1>
</div>


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

    </div>
    <div class="col-md-4" style="margin-top:20px;">
      <div class="card">
        <div class="card-header">Admin Login</div>
        <div class="card-body">
          <form method="post" id="admin_login_form">
            <div class="form-group">
              <label>Enter Username</label>
              <input type="text" name="admin_user_name" id="admin_user_name" class="form-control" />
              <span id="error_admin_user_name" class="text-danger"></span>
            </div>
            <div class="form-group">
              <label>Enter Password</label>
              <input type="password" name="admin_password" id="admin_password" class="form-control" />
              <span id="error_admin_password" class="text-danger"></span>
            </div>
            <div class="form-group">
              <input type="submit" name="admin_login" id="admin_login" class="btn btn-info" value="Login" />
            </div>
          </form>
        </div>
      </div>
    </div>
    <div class="col-md-4">

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

</body>
</html>

<script>
$(document).ready(function(){
  $('#admin_login_form').on('submit', function(event){
    event.preventDefault();
    $.ajax({
      url:"check_admin_login.php",
      method:"POST",
      data:$(this).serialize(),
      dataType:"json",
      beforeSend:function(){
        $('#admin_login').val('Validate...');
        $('#admin_login').attr('disabled', 'disabled');
      },
      success:function(data)
      {
        if(data.success)
        {
          location.href = "<?php echo $base_url; ?>admin";
        }
        if(data.error)
        {
          $('#admin_login').val('Login');
          $('#admin_login').attr('disabled', false);
          if(data.error_admin_user_name != '')
          {
            $('#error_admin_user_name').text(data.error_admin_user_name);
          }
          else
          {
            $('#error_admin_user_name').text('');
          }
          if(data.error_admin_password != '')
          {
            $('#error_admin_password').text(data.error_admin_password);
          }
          else
          {
            $('#error_admin_password').text('');
          }
        }
      }
    });
  });
});
</script>


admin/header.php



<?php

//header.php

include('database_connection.php');

session_start();

if(!isset($_SESSION["admin_id"]))
{
  header('location:login.php');
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Student Attendance System in PHP using Ajax</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">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.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>
  <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>!-->
  <link rel="stylesheet" href="../css/bootstrap.min.css">
  <link rel="stylesheet" href="../css/dataTables.bootstrap4.min.css">
  <script src="../js/jquery.min.js"></script>
  <script src="../js/popper.min.js"></script>
  <script src="../js/bootstrap.min.js"></script>
  <script src="../js/jquery.dataTables.min.js"></script>
  <script src="../js/dataTables.bootstrap4.min.js"></script>
</head>
<body>

<div class="jumbotron-small text-center" style="margin-bottom:0">
  <h1>Student Attendance System</h1>
</div>

<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
  <a class="navbar-brand" href="index.php">Home</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="grade.php">Grade</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="teacher.php">Teacher</a>
      </li>
      
      <li class="nav-item">
        <a class="nav-link" href="student.php">Student</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="attendance.php">Attendance</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="logout.php">Logout</a>
      </li>  
    </ul>
  </div>  
</nav>


admin/index.php



<?php

include('header.php');

?>

<div class="container" style="margin-top:30px">
  <div class="card">
   <div class="card-header">
      <div class="row">
        <div class="col-md-9">Overall Student Attendance Status</div>
        <div class="col-md-3" align="right">
          
        </div>
      </div>
    </div>
   <div class="card-body">
    <div class="table-responsive">
        <span id="message_operation"></span>
     <table class="table table-striped table-bordered" id="student_table">
      <thead>
       <tr>
        <th>Student Name</th>
        <th>Roll Number</th>
        <th>Grade</th>
        <th>Teacher</th>
              <th>Attendance Percentage</th>
              <th>Report</th>
       </tr>
      </thead>
      <tbody>

      </tbody>
     </table>
    </div>
   </div>
  </div>
</div>

</body>
</html>

<script type="text/javascript" src="../js/bootstrap-datepicker.js"></script>
<link rel="stylesheet" href="../css/datepicker.css" />

<style>
    .datepicker
    {
      z-index: 1600 !important; /* has to be larger than 1050 */
    }
</style>

<div class="modal" id="formModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Make Report</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
        <div class="form-group">
          <div class="input-daterange">
            <input type="text" name="from_date" id="from_date" class="form-control" placeholder="From Date" readonly />
            <span id="error_from_date" class="text-danger"></span>
            <br />
            <input type="text" name="to_date" id="to_date" class="form-control" placeholder="To Date" readonly />
            <span id="error_to_date" class="text-danger"></span>
          </div>
        </div>
      </div>
      <!-- Modal footer -->
      <div class="modal-footer">
        <input type="hidden" name="student_id" id="student_id" />
        <button type="button" name="create_report" id="create_report" class="btn btn-success btn-sm">Create Report</button>
        <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
      </div>

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

<script>
$(document).ready(function(){
 var dataTable = $('#student_table').DataTable({
  "processing":true,
  "serverSide":true,
  "order":[],
  "ajax":{
   url:"attendance_action.php",
   type:"POST",
   data:{action:'index_fetch'}
  }
 });

  $('.input-daterange').datepicker({
    todayBtn: "linked",
    format: "yyyy-mm-dd",
    autoclose: true,
    container: '#formModal modal-body'
  });

  $(document).on('click', '.report_button', function(){
    var student_id = $(this).attr('id');
    $('#student_id').val(student_id);
    $('#formModal').modal('show');
  });

  $('#create_report').click(function(){
    var student_id = $('#student_id').val();
    var from_date = $('#from_date').val();
    var to_date = $('#to_date').val();
    var error = 0;
    if(from_date == '')
    {
      $('#error_from_date').text('From Date is Required');
      error++;
    }
    else
    {
      $('#error_from_date').text('');
    }
    if(to_date == '')
    {
      $('#error_to_date').text('To Date is Required');
      error++;
    }
    else
    {
      $('#error_to_date').text('');
    }
    if(error == 0)
    {
      $('#from_date').val('');
      $('#to_date').val('');
      $('#formModal').modal('hide');
      window.open("report.php?action=student_report&student_id="+student_id+"&from_date="+from_date+"&to_date="+to_date);
    }
  });

});
</script>


admin/logout.php



<?php

//logout.php

session_start();

session_destroy();

header('location:login.php');


?>


Grade Management


admin/grade.php



<?php

include('header.php');

?>

<div class="container" style="margin-top:30px">
  <div class="card">
   <div class="card-header">
      <div class="row">
        <div class="col-md-9">Grade List</div>
        <div class="col-md-3" align="right">
          <button type="button" id="add_button" class="btn btn-info btn-sm">Add</button>
        </div>
      </div>
    </div>
   <div class="card-body">
    <div class="table-responsive">
        <span id="message_operation"></span>
     <table class="table table-striped table-bordered" id="grade_table">
      <thead>
       <tr>
        <th>Grade Name</th>
        <th>Edit</th>
        <th>Delete</th>
       </tr>
      </thead>
      <tbody>

      </tbody>
     </table>
    </div>
   </div>
  </div>
</div>

</body>
</html>

<div class="modal" id="formModal">
  <div class="modal-dialog">
    <form method="post" id="grade_form">
      <div class="modal-content">

        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title" id="modal_title"></h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>

        <!-- Modal body -->
        <div class="modal-body">
          <div class="form-group">
            <div class="row">
              <label class="col-md-4 text-right">Grade Name <span class="text-danger">*</span></label>
              <div class="col-md-8">
                <input type="text" name="grade_name" id="grade_name" class="form-control" />
                <span id="error_grade_name" class="text-danger"></span>
              </div>
            </div>
          </div>
        </div>

        <!-- Modal footer -->
        <div class="modal-footer">
          <input type="hidden" name="grade_id" id="grade_id" />
          <input type="hidden" name="action" id="action" value="Add" />
          <input type="submit" name="button_action" id="button_action" class="btn btn-success btn-sm" value="Add" />
          <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
        </div>

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


<div class="modal" id="deleteModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Delete Confirmation</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
        <h3 align="center">Are you sure you want to remove this?</h3>
      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" name="ok_button" id="ok_button" class="btn btn-primary btn-sm">OK</button>
        <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
      </div>

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


<script>
$(document).ready(function(){
 var dataTable = $('#grade_table').DataTable({
  "processing":true,
  "serverSide":true,
  "order":[],
  "ajax":{
   url:"grade_action.php",
   type:"POST",
   data:{action:'fetch'}
  },
  "columnDefs":[
   {
    "targets":[0, 1, 2],
    "orderable":false,
   },
  ],
 });

  $('#add_button').click(function(){
    $('#modal_title').text("Add Grade");
    $('#button_action').val('Add');
    $('#action').val('Add');
    $('#formModal').modal('show');
    clear_field();
  });

  function clear_field()
  {
    $('#grade_form')[0].reset();
    $('#error_grade_name').text('');
  }

  $('#grade_form').on('submit', function(event){
    event.preventDefault();
    $.ajax({
      url:"grade_action.php",
      method:"POST",
      data:$(this).serialize(),
      dataType:"json",
      beforeSend:function()
      {
        $('#button_action').attr('disabled', 'disabled');
        $('#button_action').val('Validate...');
      },
      success:function(data){
        $('#button_action').attr('disabled', false);
        $('#button_action').val($('#action').val());
        if(data.success)
        {
          $('#message_operation').html('<div class="alert alert-success">'+data.success+'</div>');
          clear_field();
          dataTable.ajax.reload();
          $('#formModal').modal('hide');
        }
        if(data.error)
        { 
          if(data.error_grade_name != '')
          {
            $('#error_grade_name').text(data.error_grade_name);
          }
          else
          {
            $('#error_grade_name').text('');
          }
        }
      }
    });
  });

  var grade_id = '';

  $(document).on('click', '.edit_grade', function(){
    grade_id = $(this).attr('id');
    clear_field();
    $.ajax({
      url:"grade_action.php",
      method:"POST",
      data:{action:'edit_fetch', grade_id:grade_id},
      dataType:"json",
      success:function(data)
      {
        $('#grade_name').val(data.grade_name);
        $('#grade_id').val(data.grade_id);
        $('#modal_title').text("Edit Grade");
        $('#button_action').val('Edit');
        $('#action').val('Edit');
        $('#formModal').modal('show');
      }
    });
  });

  $(document).on('click', '.delete_grade', function(){
    grade_id = $(this).attr('id');
    $('#deleteModal').modal('show');
  });

  $('#ok_button').click(function(){
    $.ajax({
      url:"grade_action.php",
      method:"POST",
      data:{grade_id:grade_id, action:'delete'},
      success:function(data)
      {
        $('#message_operation').html('<div class="alert alert-success">'+data+'</div>');
        $('#deleteModal').modal('hide');
        dataTable.ajax.reload();
      }
    });
  });

});
</script>


admin/grade_action.php



<?php

//grade_action.php

include('database_connection.php');
session_start();
$output = '';
if(isset($_POST["action"]))
{
 if($_POST["action"] == 'fetch')
 {
  $query = "SELECT * FROM tbl_grade ";
  if(isset($_POST["search"]["value"]))
  {
   $query .= 'WHERE grade_name LIKE "%'.$_POST["search"]["value"].'%" ';
  }
  if(isset($_POST["order"]))
  {
   $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
  }
  else
  {
   $query .= 'ORDER BY grade_id DESC ';
  }
  if($_POST["length"] != -1)
  {
   $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
  }

  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  $data = array();
  $filtered_rows = $statement->rowCount();
  foreach($result as $row)
  {
   $sub_array = array();
   $sub_array[] = $row["grade_name"];
   $sub_array[] = '<button type="button" name="edit_grade" class="btn btn-primary btn-sm edit_grade" id="'.$row["grade_id"].'">Edit</button>';
   $sub_array[] = '<button type="button" name="delete_grade" class="btn btn-danger btn-sm delete_grade" id="'.$row["grade_id"].'">Delete</button>';
   $data[] = $sub_array;
  }

  $output = array(
   "draw"    => intval($_POST["draw"]),
   "recordsTotal"  =>  $filtered_rows,
   "recordsFiltered" => get_total_records($connect, 'tbl_grade'),
   "data"    => $data
  );
  echo json_encode($output);
 }

 if($_POST["action"] == 'Add' || $_POST["action"] == "Edit")
 {
  $grade_name = '';
  $error_grade_name = '';
  $error = 0;

  if(empty($_POST["grade_name"]))
  {
   $error_grade_name = 'Grade Name is required';
   $error++;
  }
  else
  {
   $grade_name = $_POST["grade_name"];
  }
  if($error > 0)
  {
   $output = array(
    'error'       => true,
    'error_grade_name'    => $error_grade_name
   );
  }
  else
  {
   if($_POST["action"] == "Add")
   {
    $data = array(
     ':grade_name'    => $grade_name
    );
    $query = "
    INSERT INTO tbl_grade 
    (grade_name) 
    SELECT * FROM (SELECT :grade_name) as temp 
    WHERE NOT EXISTS (
     SELECT grade_name FROM tbl_grade WHERE grade_name = :grade_name
    ) LIMIT 1
    ";
    $statement = $connect->prepare($query);
    if($statement->execute($data))
    {
     if($statement->rowCount() > 0)
     {
      $output = array(
       'success'  => 'Data Added Successfully',
      );
     }
     else
     {
      $output = array(
       'error'     => true,
       'error_grade_name' => 'Grade Name Already Exists'
      );
     }
    }
   }
   if($_POST["action"] == "Edit")
   {
    $data = array(
     ':grade_name'    => $grade_name,
     ':grade_id'     => $_POST["grade_id"]
    );
    $query = "
    UPDATE tbl_grade 
    SET grade_name = :grade_name 
    WHERE grade_id = :grade_id
    ";
    $statement = $connect->prepare($query);
    if($statement->execute($data))
    {
     $output = array(
      'success'  => 'Data Updated Successfully',
     );
    }
   }
  }
  echo json_encode($output);
 }

 if($_POST["action"] == "edit_fetch")
 {
  $query = "SELECT * FROM tbl_grade WHERE grade_id = '".$_POST["grade_id"]."'";
  $statement = $connect->prepare($query);
  if($statement->execute())
  {
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    $output['grade_name'] = $row["grade_name"];
    $output['grade_id'] = $row['grade_id'];
   }
   echo json_encode($output);
  }
 }

 if($_POST["action"] == "delete")
 {
  $query = "DELETE FROM tbl_grade WHERE grade_id = '".$_POST["grade_id"]."'";
  $statement = $connect->prepare($query);
  if($statement->execute())
  {
   echo 'Data Delete Successfully';
  }
 }
}

?>


Teacher Management


admin/teacher.php



<?php

include('header.php');

?>

<div class="container" style="margin-top:30px">
  <div class="card">
   <div class="card-header">
      <div class="row">
        <div class="col-md-9">Teacher List</div>
        <div class="col-md-3" align="right">
          <button type="button" id="add_button" class="btn btn-info btn-sm">Add</button>
        </div>
      </div>
    </div>
   <div class="card-body">
    <div class="table-responsive">
        <span id="message_operation"></span>
     <table class="table table-striped table-bordered" id="teacher_table">
      <thead>
       <tr>
        <th>Image</th>
        <th>Teacher Name</th>
        <th>Email Address</th>
              <th>Grade</th>
        <th>View</th>
        <th>Edit</th>
        <th>Delete</th>
       </tr>
      </thead>
      <tbody>

      </tbody>
     </table>
    </div>
   </div>
  </div>
</div>

</body>
</html>

<script type="text/javascript" src="https://www.eyecon.ro/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
<link rel="stylesheet" href="https://www.eyecon.ro/bootstrap-datepicker/css/datepicker.css" />

<style>
    .datepicker {
      z-index: 1600 !important; /* has to be larger than 1050 */
    }
</style>

<div class="modal" id="formModal">
  <div class="modal-dialog">
    <form method="post" id="teacher_form" enctype="multipart/form-data">
      <div class="modal-content">

        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title" id="modal_title"></h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>

        <!-- Modal body -->
        <div class="modal-body">
          <div class="form-group">
            <div class="row">
              <label class="col-md-4 text-right">Teacher Name <span class="text-danger">*</span></label>
              <div class="col-md-8">
                <input type="text" name="teacher_name" id="teacher_name" class="form-control" />
                <span id="error_teacher_name" class="text-danger"></span>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row">
              <label class="col-md-4 text-right">Address <span class="text-danger">*</span></label>
              <div class="col-md-8">
                <textarea name="teacher_address" id="teacher_address" class="form-control"></textarea>
                <span id="error_teacher_address" class="text-danger"></span>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row">
              <label class="col-md-4 text-right">Email Address <span class="text-danger">*</span></label>
              <div class="col-md-8">
                <input type="text" name="teacher_emailid" id="teacher_emailid" class="form-control" />
                <span id="error_teacher_emailid" class="text-danger"></span>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row">
              <label class="col-md-4 text-right">Password <span class="text-danger">*</span></label>
              <div class="col-md-8">
                <input type="password" name="teacher_password" id="teacher_password" class="form-control" />
                <span id="error_teacher_password" class="text-danger"></span>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row">
              <label class="col-md-4 text-right">Qualification <span class="text-danger">*</span></label>
              <div class="col-md-8">
                <input type="text" name="teacher_qualification" id="teacher_qualification" class="form-control" />
                <span id="error_teacher_qualification" class="text-danger"></span>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row">
              <label class="col-md-4 text-right">Grade <span class="text-danger">*</span></label>
              <div class="col-md-8">
                <select name="teacher_grade_id" id="teacher_grade_id" class="form-control">
                  <option value="">Select Grade</option>
                  <?php
                  echo load_grade_list($connect);
                  ?>
                </select>
                <span id="error_teacher_grade_id" class="text-danger"></span>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row">
              <label class="col-md-4 text-right">Date of Joining <span class="text-danger">*</span></label>
              <div class="col-md-8">
                <input type="text" name="teacher_doj" id="teacher_doj" class="form-control" />
                <span id="error_teacher_doj" class="text-danger"></span>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row">
              <label class="col-md-4 text-right">Image <span class="text-danger">*</span></label>
              <div class="col-md-8">
                <input type="file" name="teacher_image" id="teacher_image" />
                <span class="text-muted">Only .jpg and .png allowed</span><br />
                <span id="error_teacher_image" class="text-danger"></span>
              </div>
            </div>
          </div>
        </div>

        <!-- Modal footer -->
        <div class="modal-footer">
          <input type="hidden" name="hidden_teacher_image" id="hidden_teacher_image" value="" />
          <input type="hidden" name="teacher_id" id="teacher_id" />
          <input type="hidden" name="action" id="action" value="Add" />
          <input type="submit" name="button_action" id="button_action" class="btn btn-success btn-sm" value="Add" />
          <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
        </div>

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

<div class="modal" id="viewModal">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Teacher Details</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body" id="teacher_details">

      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
      </div>

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


<div class="modal" id="deleteModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Delete Confirmation</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
        <h3 align="center">Are you sure you want to remove this?</h3>
      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" name="ok_button" id="ok_button" class="btn btn-primary btn-sm">OK</button>
        <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
      </div>

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


<script>
$(document).ready(function(){
 var dataTable = $('#teacher_table').DataTable({
  "processing":true,
  "serverSide":true,
  "order":[],
  "ajax":{
   url:"teacher_action.php",
   type:"POST",
   data:{action:'fetch'}
  },
  "columnDefs":[
   {
    "targets":[0, 4, 5, 6],
    "orderable":false,
   },
  ],
 });

  $('#teacher_doj').datepicker({
        format: "yyyy-mm-dd",
        autoclose: true,
        container: '#formModal modal-body'
    });

  function clear_field()
  {
    $('#teacher_form')[0].reset();
    $('#error_teacher_name').text('');
    $('#error_teacher_address').text('');
    $('#error_teacher_emailid').text('');
    $('#error_teacher_password').text('');
    $('#error_teacher_qualification').text('');
    $('#error_teacher_doj').text('');
    $('#error_teacher_image').text('');
    $('#error_teacher_grade_id').text('');
  }

  $('#add_button').click(function(){
    $('#modal_title').text("Add Teacher");
    $('#button_action').val('Add');
    $('#action').val('Add');
    $('#formModal').modal('show');
    clear_field();
  });

  $('#teacher_form').on('submit', function(event){
    event.preventDefault();
    $.ajax({
      url:"teacher_action.php",
      method:"POST",
      data:new FormData(this),
      dataType:"json",
      contentType:false,
      processData:false,
      beforeSend:function()
      {        
        $('#button_action').val('Validate...');
        $('#button_action').attr('disabled', 'disabled');
      },
      success:function(data){
        $('#button_action').attr('disabled', false);
        $('#button_action').val($('#action').val());
        if(data.success)
        {
          $('#message_operation').html('<div class="alert alert-success">'+data.success+'</div>');
          clear_field();
          $('#formModal').modal('hide');
          dataTable.ajax.reload();
        }
        if(data.error)
        { 
          if(data.error_teacher_name != '')
          {
            $('#error_teacher_name').text(data.error_teacher_name);
          }
          else
          {
            $('#error_teacher_name').text('');
          }
          if(data.error_teacher_address != '')
          {
            $('#error_teacher_address').text(data.error_teacher_address);
          }
          else
          {
            $('#error_teacher_address').text('');
          }
          if(data.error_teacher_emailid != '')
          {
            $('#error_teacher_emailid').text(data.error_teacher_emailid);
          }
          else
          {
            $('#error_teacher_emailid').text('');
          }
          if(data.error_teacher_password != '')
          {
            $('#error_teacher_password').text(data.error_teacher_password);
          }
          else
          {
            $('#error_teacher_password').text('');
          }
          if(data.error_teacher_grade_id != '')
          {
            $('#error_teacher_grade_id').text(data.error_teacher_grade_id);
          }
          else
          {
            $('#error_teacher_grade_id').text('');
          }
          if(data.error_teacher_qualification != '')
          {
            $('#error_teacher_qualification').text(data.error_teacher_qualification);
          }
          else
          {
            $('#error_teacher_qualification').text('');
          }
          if(data.error_teacher_doj != '')
          {
            $('#error_teacher_doj').text(data.error_teacher_doj);
          }
          else
          {
            $('#error_teacher_doj').text('');
          }
          if(data.error_teacher_image != '')
          {
            $('#error_teacher_image').text(data.error_teacher_image);
          }
          else
          {
            $('#error_teacher_image').text('');
          }
        }
      }
    });
  });

  var teacher_id = '';

  $(document).on('click', '.view_teacher', function(){
    teacher_id = $(this).attr('id');
    $.ajax({
      url:"teacher_action.php",
      method:"POST",
      data:{action:'single_fetch', teacher_id:teacher_id},
      success:function(data)
      {
        $('#viewModal').modal('show');
        $('#teacher_details').html(data);
      }
    });
  });

  $(document).on('click', '.edit_teacher', function(){
    teacher_id = $(this).attr('id');
    clear_field();
    $.ajax({
      url:"teacher_action.php",
      method:"POST",
      data:{action:'edit_fetch', teacher_id:teacher_id},
      dataType:"json",
      success:function(data)
      {
        $('#teacher_name').val(data.teacher_name);
        $('#teacher_address').val(data.teacher_address);
        //$('#teacher_emailid').val(data.teacher_emailid);
        $('#teacher_grade_id').val(data.teacher_grade_id);
        $('#teacher_qualification').val(data.teacher_qualification);
        $('#teacher_doj').val(data.teacher_doj);
        $('#error_teacher_image').html('<img src="teacher_image/'+data.teacher_image+'" class="img-thumbnail" width="50" />');
        $('#hidden_teacher_image').val(data.teacher_image);
        $('#teacher_id').val(data.teacher_id);
        $('#modal_title').text("Edit Teacher");
        $('#button_action').val('Edit');
        $('#action').val('Edit');
        $('#formModal').modal('show');
      }
    });
  });

  $(document).on('click', '.delete_teacher', function(){
    teacher_id = $(this).attr('id');
    $('#deleteModal').modal('show');
  });

  $('#ok_button').click(function(){
    $.ajax({
      url:"teacher_action.php",
      method:"POST",
      data:{teacher_id:teacher_id, action:'delete'},
      success:function(data)
      {
        $('#message_operation').html('<div class="alert alert-success">'+data+'</div>');
        $('#deleteModal').modal('hide');
        dataTable.ajax.reload();
      }
    });
  });

});
</script>


admin/teacher_action.php



<?php

//teacher_action.php

include('database_connection.php');
session_start();
$output = '';
if(isset($_POST["action"]))
{
 if($_POST["action"] == 'fetch')
 {
  $query = "
  SELECT * FROM tbl_teacher 
  INNER JOIN tbl_grade 
  ON tbl_grade.grade_id = tbl_teacher.teacher_grade_id ";
  if(isset($_POST["search"]["value"]))
  {
   $query .= 'WHERE tbl_teacher.teacher_name LIKE "%'.$_POST["search"]["value"].'%" 
      OR tbl_teacher.teacher_emailid LIKE "%'.$_POST["search"]["value"].'%" 
      OR tbl_grade.grade_name LIKE "%'.$_POST["search"]["value"].'%" ';
  }
  if(isset($_POST["order"]))
  {
   $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
  }
  else
  {
   $query .= 'ORDER BY tbl_teacher.teacher_id DESC ';
  }
  if($_POST["length"] != -1)
  {
   $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
  }

  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  $data = array();
  $filtered_rows = $statement->rowCount();
  foreach($result as $row)
  {
   $sub_array = array();
   $sub_array[] = '<img src="teacher_image/'.$row["teacher_image"].'" class="img-thumbnail" width="75" />';
   $sub_array[] = $row["teacher_name"];
   $sub_array[] = $row["teacher_emailid"];
   $sub_array[] = $row["grade_name"];
   $sub_array[] = '<button type="button" name="view_teacher" class="btn btn-info btn-sm view_teacher" id="'.$row["teacher_id"].'">View</button>';
   $sub_array[] = '<button type="button" name="edit_teacher" class="btn btn-primary btn-sm edit_teacher" id="'.$row["teacher_id"].'">Edit</button>';
   $sub_array[] = '<button type="button" name="delete_teacher" class="btn btn-danger btn-sm delete_teacher" id="'.$row["teacher_id"].'">Delete</button>';
   $data[] = $sub_array;
  }

  $output = array(
   "draw"    => intval($_POST["draw"]),
   "recordsTotal"  =>  $filtered_rows,
   "recordsFiltered" => get_total_records($connect, 'tbl_teacher'),
   "data"    => $data
  );
  echo json_encode($output);
 }

 if($_POST["action"] == 'Add' || $_POST["action"] == "Edit")
 {
  $teacher_name = '';
  $teacher_address = '';
  $teacher_emailid = '';
  $teacher_password = '';
  $teacher_grade_id = '';
  $teacher_qualification = '';
  $teacher_doj = '';
  $teacher_image = '';
  $error_teacher_name = '';
  $error_teacher_address = '';
  $error_teacher_emailid = '';
  $error_teacher_password = '';
  $error_teacher_grade_id = '';
  $error_teacher_qualification = '';
  $error_teacher_doj = '';
  $error_teacher_image = '';
  $error = 0;

  $teacher_image = $_POST["hidden_teacher_image"];
  if($_FILES["teacher_image"]["name"] != '')
  {
   $file_name = $_FILES["teacher_image"]["name"];
   $tmp_name = $_FILES["teacher_image"]['tmp_name'];
   $extension_array = explode(".", $file_name);
   $extension = strtolower($extension_array[1]);
   $allowed_extension = array('jpg','png');
   if(!in_array($extension, $allowed_extension))
   {
    $error_teacher_image = 'Invalid Image Format';
    $error++;
   }
   else
   {
    $teacher_image = uniqid() . '.' . $extension;
    $upload_path = 'teacher_image/' . $teacher_image;    
    move_uploaded_file($tmp_name, $upload_path);
   } 
  }
  else
  {
   if($teacher_image == '')
   {
    $error_teacher_image = $teacher_image;
    $error++;
   }
  }
  if(empty($_POST["teacher_name"]))
  {
   $error_teacher_name = 'Teacher Name is required';
   $error++;
  }
  else
  {
   $teacher_name = $_POST["teacher_name"];
  }
  if(empty($_POST["teacher_address"]))
  {
   $error_teacher_address = 'Teacher Address is required';
   $error++;
  }
  else
  {
   $teacher_address = $_POST["teacher_address"];
  }
  if($_POST["action"] == "Add")
  {
   if(empty($_POST["teacher_emailid"]))
   {
    $error_teacher_emailid = 'Email Address is required';
    $error++;
   }
   else
   {
    if (!filter_var($_POST["teacher_emailid"], FILTER_VALIDATE_EMAIL))
    {
          $error_teacher_emailid = "Invalid email format"; 
          $error++;
       }
       else
       {
     $teacher_emailid = $_POST["teacher_emailid"];
    }
   }
  
   if(empty($_POST["teacher_password"]))
   {
    $error_teacher_password = 'Password is required';
    $error++;
   }
   else
   {
    $teacher_password = $_POST["teacher_password"];
   }
  }

  if(empty($_POST["teacher_grade_id"]))
  {
   $error_teacher_grade_id = 'Grade is required';
    $error++;
  }
  else
  {
   $teacher_grade_id = $_POST["teacher_grade_id"];
  }

  if(empty($_POST["teacher_qualification"]))
  {
   $error_teacher_qualification = 'Qualification Field is required';
   $error++;
  }
  else
  {
   $teacher_qualification = $_POST["teacher_qualification"];
  }
  if(empty($_POST["teacher_doj"]))
  {
   $error_teacher_doj = 'Date of Join Field is required';
   $error++;
  }
  else
  {
   $teacher_doj = $_POST["teacher_doj"];
  }
  if($error > 0)
  {
   $output = array(
    'error'       => true,
    'error_teacher_name'   => $error_teacher_name,
    'error_teacher_address'   => $error_teacher_address,
    'error_teacher_emailid'   => $error_teacher_emailid,
    'error_teacher_password'  => $error_teacher_password,
    'error_teacher_grade_id'  => $error_teacher_grade_id,
    'error_teacher_qualification' => $error_teacher_qualification,
    'error_teacher_doj'    => $error_teacher_doj,
    'error_teacher_image'   => $error_teacher_image
   );
  }
  else
  {
   if($_POST["action"] == "Add")
   {
    $data = array(
     ':teacher_name'    => $teacher_name,
     ':teacher_address'   => $teacher_address,
     ':teacher_emailid'   => $teacher_emailid,
     ':teacher_password'   => password_hash($teacher_password, PASSWORD_DEFAULT),
     ':teacher_qualification' => $teacher_qualification,
     ':teacher_doj'    => $teacher_doj,
     ':teacher_image'   => $teacher_image,
     ':teacher_grade_id'   => $teacher_grade_id
    );
    $query = "
    INSERT INTO tbl_teacher 
    (teacher_name, teacher_address, teacher_emailid, teacher_password, teacher_qualification, teacher_doj, teacher_image, teacher_grade_id) 
    SELECT * FROM (SELECT :teacher_name, :teacher_address, :teacher_emailid, :teacher_password, :teacher_qualification, :teacher_doj, :teacher_image, :teacher_grade_id) as temp 
    WHERE NOT EXISTS (
     SELECT teacher_emailid FROM tbl_teacher WHERE teacher_emailid = :teacher_emailid
    ) LIMIT 1
    ";
    $statement = $connect->prepare($query);
    if($statement->execute($data))
    {
     if($statement->rowCount() > 0)
     {
      $output = array(
       'success'  => 'Data Added Successfully',
      );
     }
     else
     {
      $output = array(
       'error'     => true,
       'error_teacher_emailid' => 'Email Already Exists'
      );
     }
    }
   }
   if($_POST["action"] == "Edit")
   {
    $data = array(
     ':teacher_name'    => $teacher_name,
     ':teacher_address'   => $teacher_address,
     ':teacher_qualification' => $teacher_qualification,
     ':teacher_doj'    => $teacher_doj,
     ':teacher_image'   => $teacher_image,
     ':teacher_grade_id'   => $teacher_grade_id,
     ':teacher_id'    => $_POST["teacher_id"]
    );
    $query = "
    UPDATE tbl_teacher 
    SET teacher_name = :teacher_name, 
    teacher_address = :teacher_address,  
    teacher_grade_id = :teacher_grade_id, 
    teacher_qualification = :teacher_qualification, 
    teacher_doj = :teacher_doj, 
    teacher_image = :teacher_image
    WHERE teacher_id = :teacher_id
    ";
    $statement = $connect->prepare($query);
    if($statement->execute($data))
    {
     $output = array(
      'success'  => 'Data Edited Successfully',
     );
    }
   }
  }
  echo json_encode($output);
 }

 if($_POST["action"] == 'single_fetch')
 {
  $query = "
  SELECT * FROM tbl_teacher 
  INNER JOIN tbl_grade 
  ON tbl_grade.grade_id = tbl_teacher.teacher_grade_id 
  WHERE tbl_teacher.teacher_id = '".$_POST["teacher_id"]."'";
  $statement = $connect->prepare($query);
  if($statement->execute())
  {
   $result = $statement->fetchAll();
   $output = '
   <div class="row">
   ';
   foreach($result as $row)
   {
    $output .= '
    <div class="col-md-3">
     <img src="teacher_image/'.$row["teacher_image"].'" class="img-thumbnail" />
    </div>
    <div class="col-md-9">
     <table class="table">
      <tr>
       <th>Name</th>
       <td>'.$row["teacher_name"].'</td>
      </tr>
      <tr>
       <th>Address</th>
       <td>'.$row["teacher_address"].'</td>
      </tr>
      <tr>
       <th>Email Address</th>
       <td>'.$row["teacher_emailid"].'</td>
      </tr>
      <tr>
       <th>Qualification</th>
       <td>'.$row["teacher_qualification"].'</td>
      </tr>
      <tr>
       <th>Date of Joining</th>
       <td>'.$row["teacher_doj"].'</td>
      </tr>
      <tr>
       <th>Grade</th>
       <td>'.$row["grade_name"].'</td>
      </tr>
     </table>
    </div>
    ';
   }
   $output .= '</div>';
   echo $output;
  }
 }

 if($_POST["action"] == "edit_fetch")
 {
  $query = "SELECT * FROM tbl_teacher WHERE teacher_id = '".$_POST["teacher_id"]."'";
  $statement = $connect->prepare($query);
  if($statement->execute())
  {
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    $output['teacher_name'] = $row["teacher_name"];
    $output['teacher_address'] = $row['teacher_address'];
    //$output['teacher_emailid'] = $row['teacher_emailid'];
    $output['teacher_qualification'] = $row['teacher_qualification'];
    $output['teacher_doj'] = $row['teacher_doj'];
    $output['teacher_image'] = $row['teacher_image'];
    $output['teacher_grade_id'] = $row['teacher_grade_id'];
    $output['teacher_id'] = $row['teacher_id'];
   }
   echo json_encode($output);
  }
 }

 if($_POST["action"] == "delete")
 {
  $query = "DELETE FROM tbl_teacher WHERE teacher_id = '".$_POST["teacher_id"]."'";
  $statement = $connect->prepare($query);
  if($statement->execute())
  {
   echo 'Data Delete Successfully';
  }
 }
}

?>


Student Management


admin/student.php



<?php

include('header.php');

?>

<div class="container" style="margin-top:30px">
  <div class="card">
   <div class="card-header">
      <div class="row">
        <div class="col-md-9">Student List</div>
        <div class="col-md-3" align="right">
          <button type="button" id="add_button" class="btn btn-info btn-sm">Add</button>
        </div>
      </div>
    </div>
   <div class="card-body">
    <div class="table-responsive">
        <span id="message_operation"></span>
     <table class="table table-striped table-bordered" id="student_table">
      <thead>
       <tr>
        <th>Student Name</th>
        <th>Roll No.</th>
        <th>Date of Birth</th>
              <th>Grade</th>
        <th>Edit</th>
        <th>Delete</th>
       </tr>
      </thead>
      <tbody>

      </tbody>
     </table>
    </div>
   </div>
  </div>
</div>

</body>
</html>

<script type="text/javascript" src="https://www.eyecon.ro/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
<link rel="stylesheet" href="https://www.eyecon.ro/bootstrap-datepicker/css/datepicker.css" />

<style>
    .datepicker {
      z-index: 1600 !important; /* has to be larger than 1050 */
    }
</style>

<div class="modal" id="formModal">
  <div class="modal-dialog">
    <form method="post" id="student_form">
      <div class="modal-content">

        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title" id="modal_title"></h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>

        <!-- Modal body -->
        <div class="modal-body">
          <div class="form-group">
            <div class="row">
              <label class="col-md-4 text-right">Student Name <span class="text-danger">*</span></label>
              <div class="col-md-8">
                <input type="text" name="student_name" id="student_name" class="form-control" />
                <span id="error_student_name" class="text-danger"></span>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row">
              <label class="col-md-4 text-right">Roll No. <span class="text-danger">*</span></label>
              <div class="col-md-8">
                <input type="text" name="student_roll_number" id="student_roll_number" class="form-control" />
                <span id="error_student_roll_number" class="text-danger"></span>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row">
              <label class="col-md-4 text-right">Date of Birth <span class="text-danger">*</span></label>
              <div class="col-md-8">
                <input type="text" name="student_dob" id="student_dob" class="form-control" />
                <span id="error_student_dob" class="text-danger"></span>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row">
              <label class="col-md-4 text-right">Grade <span class="text-danger">*</span></label>
              <div class="col-md-8">
                <select name="student_grade_id" id="student_grade_id" class="form-control">
                  <option value="">Select Grade</option>
                  <?php
                  echo load_grade_list($connect);
                  ?>
                </select>
                <span id="error_student_grade_id" class="text-danger"></span>
              </div>
            </div>
          </div>
        </div>

        <!-- Modal footer -->
        <div class="modal-footer">
          <input type="hidden" name="student_id" id="student_id" />
          <input type="hidden" name="action" id="action" value="Add" />
          <input type="submit" name="button_action" id="button_action" class="btn btn-success btn-sm" value="Add" />
          <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
        </div>

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

<div class="modal" id="deleteModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Delete Confirmation</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
        <h3 align="center">Are you sure you want to remove this?</h3>
      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" name="ok_button" id="ok_button" class="btn btn-primary btn-sm">OK</button>
        <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
      </div>

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


<script>
$(document).ready(function(){
 var dataTable = $('#student_table').DataTable({
  "processing":true,
  "serverSide":true,
  "order":[],
  "ajax":{
   url:"student_action.php",
   type:"POST",
   data:{action:'fetch'}
  },
  "columnDefs":[
   {
    "targets":[4, 5],
    "orderable":false,
   },
  ],
 });

  $('#student_dob').datepicker({
        format: "yyyy-mm-dd",
        autoclose: true,
        container: '#formModal modal-body'
    });

  function clear_field()
  {
    $('#student_form')[0].reset();
    $('#error_student_name').text('');
    $('#error_student_roll_number').text('');
    $('#error_student_dob').text('');
    $('#error_student_grade_id').text('');
  }

  $('#add_button').click(function(){
    $('#modal_title').text("Add Student");
    $('#button_action').val('Add');
    $('#action').val('Add');
    $('#formModal').modal('show');
    clear_field();
  });

  

  $('#student_form').on('submit', function(event){
    event.preventDefault();
    $.ajax({
      url:"student_action.php",
      method:"POST",
      data:$(this).serialize(),
      dataType:"json",
      beforeSend:function()
      {
        $('#button_action').attr('disabled', 'disabled');
        $('#button_action').val('Validate...');
      },
      success:function(data){
        $('#button_action').attr('disabled', false);
        $('#button_action').val($('#action').val());
        if(data.success)
        {
          $('#message_operation').html('<div class="alert alert-success">'+data.success+'</div>');
          clear_field();
          $('#formModal').modal('hide');
          dataTable.ajax.reload();
        }
        if(data.error)
        { 
          if(data.error_student_name != '')
          {
            $('#error_student_name').text(data.error_student_name);
          }
          else
          {
            $('#error_student_name').text('');
          }
          if(data.error_student_roll_number != '')
          {
            $('#error_student_roll_number').text(data.error_student_roll_number);
          }
          else
          {
            $('#error_student_roll_number').text('');
          }
          if(data.error_student_dob != '')
          {
            $('#error_student_dob').text(data.error_student_dob);
          }
          else
          {
            $('#error_student_dob').text('');
          }
          if(data.error_student_grade_id != '')
          {
            $('#error_student_grade_id').text(data.error_student_grade_id);
          }
          else
          {
            $('#error_student_grade_id').text('');
          }
        }
      }
    });
  });

  var student_id = '';

  $(document).on('click', '.edit_student', function(){
    student_id = $(this).attr('id');
    clear_field();
    $.ajax({
      url:"student_action.php",
      method:"POST",
      data:{action:'edit_fetch', student_id:student_id},
      dataType:"json",
      success:function(data)
      {
        $('#student_name').val(data.student_name);
        $('#student_roll_number').val(data.student_roll_number);
        $('#student_dob').val(data.student_dob);
        //$('#teacher_qualification').val(data.teacher_qualification);
        //$('#teacher_doj').val(data.teacher_doj);
        $('#student_grade_id').val(data.student_grade_id);
        $('#student_id').val(data.student_id);
        $('#modal_title').text("Edit Student");
        $('#button_action').val('Edit');
        $('#action').val('Edit');
        $('#formModal').modal('show');
      }
    });
  });

  $(document).on('click', '.delete_student', function(){
    student_id = $(this).attr('id');
    $('#deleteModal').modal('show');
  });

  $('#ok_button').click(function(){
    $.ajax({
      url:"student_action.php",
      method:"POST",
      data:{student_id:student_id, action:'delete'},
      success:function(data)
      {
        $('#message_operation').html('<div class="alert alert-success">'+data+'</div>');
        $('#deleteModal').modal('hide');
        dataTable.ajax.reload();
      }
    });
  });

});
</script>


admin/student_action.php



<?php

//student_action.php

include('database_connection.php');
session_start();
$output = '';
if(isset($_POST["action"]))
{
 if($_POST["action"] == 'fetch')
 {
  $query = "
  SELECT * FROM tbl_student 
  INNER JOIN tbl_grade 
  ON tbl_grade.grade_id = tbl_student.student_grade_id ";
  if(isset($_POST["search"]["value"]))
  {
   $query .= 'WHERE tbl_student.student_name LIKE "%'.$_POST["search"]["value"].'%" 
      OR tbl_student.student_roll_number LIKE "%'.$_POST["search"]["value"].'%" 
      OR tbl_student.student_dob LIKE "%'.$_POST["search"]["value"].'%" 
      OR tbl_grade.grade_name LIKE "%'.$_POST["search"]["value"].'%" ';
  }
  if(isset($_POST["order"]))
  {
   $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
  }
  else
  {
   $query .= 'ORDER BY tbl_student.student_id DESC ';
  }
  if($_POST["length"] != -1)
  {
   $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
  }

  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  $data = array();
  $filtered_rows = $statement->rowCount();
  foreach($result as $row)
  {
   $sub_array = array();
   $sub_array[] = $row["student_name"];
   $sub_array[] = $row["student_roll_number"];
   $sub_array[] = $row["student_dob"];
   $sub_array[] = $row["grade_name"];
   $sub_array[] = '<button type="button" name="edit_student" class="btn btn-primary btn-sm edit_student" id="'.$row["student_id"].'">Edit</button>';
   $sub_array[] = '<button type="button" name="delete_student" class="btn btn-danger btn-sm delete_student" id="'.$row["student_id"].'">Delete</button>';
   $data[] = $sub_array;
  }

  $output = array(
   "draw"    => intval($_POST["draw"]),
   "recordsTotal"  =>  $filtered_rows,
   "recordsFiltered" => get_total_records($connect, 'tbl_student'),
   "data"    => $data
  );
  echo json_encode($output);
 }

 if($_POST["action"] == 'Add' || $_POST["action"] == "Edit")
 {
  $student_name = '';
  $student_roll_number = '';
  $student_dob = '';
  $student_grade_id = '';
  $error_student_name = '';
  $error_student_roll_number = '';
  $error_student_dob = '';
  $error_student_grade_id = '';
  $error = 0;

  
  if(empty($_POST["student_name"]))
  {
   $error_student_name = 'Student Name is required';
   $error++;
  }
  else
  {
   $student_name = $_POST["student_name"];
  }
  if(empty($_POST["student_roll_number"]))
  {
   $error_student_roll_number = 'Student Roll Number is required';
   $error++;
  }
  else
  {
   $student_roll_number = $_POST["student_roll_number"];
  }
  if(empty($_POST["student_dob"]))
  {
   $error_student_dob = 'Student Date of Birth is required';
   $error++;
  }
  else
  {
   $student_dob = $_POST["student_dob"];
  }
  if(empty($_POST["student_grade_id"]))
  {
   $error_student_grade_id = 'Grade is required';
   $error++;
  }
  else
  {
   $student_grade_id = $_POST["student_grade_id"];
  }
  
  if($error > 0)
  {
   $output = array(
    'error'       => true,
    'error_student_name'   => $error_student_name,
    'error_student_roll_number'  => $error_student_roll_number,
    'error_student_dob'    => $error_student_dob,
    'error_student_grade_id'  => $error_student_grade_id
   );
  }
  else
  {
   if($_POST["action"] == "Add")
   {
    $data = array(
     ':student_name'    => $student_name,
     ':student_roll_number'  => $student_roll_number,
     ':student_dob'    => $student_dob,
     ':student_grade_id'   => $student_grade_id
    );
    $query = "
    INSERT INTO tbl_student 
    (student_name, student_roll_number, student_dob, student_grade_id) 
    VALUES (:student_name, :student_roll_number, :student_dob, :student_grade_id)
    ";
    $statement = $connect->prepare($query);
    if($statement->execute($data))
    {
     $output = array(
      'success'  => 'Data Added Successfully',
     );
    }
   }
   if($_POST["action"] == "Edit")
   {
    $data = array(
     ':student_name'    => $student_name,
     ':student_roll_number'  => $student_roll_number,
     ':student_dob'    => $student_dob,
     ':student_grade_id'   => $student_grade_id,
     ':student_id'    => $_POST["student_id"]
    );
    $query = "
    UPDATE tbl_student 
    SET student_name = :student_name, 
    student_roll_number = :student_roll_number, 
    student_dob = :student_dob, 
    student_grade_id = :student_grade_id 
    WHERE student_id = :student_id
    ";
    $statement = $connect->prepare($query);
    if($statement->execute($data))
    {
     $output = array(
      'success'  => 'Data Edited Successfully',
     );
    }
   }
  }
  echo json_encode($output);
 }

 if($_POST["action"] == "edit_fetch")
 {
  $query = "SELECT * FROM tbl_student WHERE student_id = '".$_POST["student_id"]."'";
  $statement = $connect->prepare($query);
  if($statement->execute())
  {
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    $output['student_name'] = $row["student_name"];
    $output['student_roll_number'] = $row['student_roll_number'];
    $output['student_dob'] = $row['student_dob'];
    $output['student_grade_id'] = $row['student_grade_id'];
    $output['student_id'] = $row['student_id'];
   }
   echo json_encode($output);
  }
 }

 if($_POST["action"] == "delete")
 {
  $query = "
  DELETE FROM tbl_student 
  WHERE student_id = '".$_POST["student_id"]."'";
  $statement = $connect->prepare($query);
  if($statement->execute())
  {
   echo 'Data Delete Successfully';
  }
 }
}

?>


Teacher Login


login.php



<?php

//login.php

include('admin/database_connection.php');

session_start();

if(isset($_SESSION["teacher_id"]))
{
  header('location:index.php');
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Student Attendance System in PHP using Ajax</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://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>
</head>
<body>

<div class="jumbotron text-center" style="margin-bottom:0">
  <h1>Student Attendance System</h1>
</div>


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

    </div>
    <div class="col-md-4" style="margin-top:20px;">
      <div class="card">
        <div class="card-header">Teacher Login</div>
        <div class="card-body">
          <form method="post" id="teacher_login_form">
            <div class="form-group">
              <label>Enter Email Address</label>
              <input type="text" name="teacher_emailid" id="teacher_emailid" class="form-control" />
              <span id="error_teacher_emailid" class="text-danger"></span>
            </div>
            <div class="form-group">
              <label>Enter Password</label>
              <input type="password" name="teacher_password" id="teacher_password" class="form-control" />
              <span id="error_teacher_password" class="text-danger"></span>
            </div>
            <div class="form-group">
              <input type="submit" name="teacher_login" id="teacher_login" class="btn btn-info" value="Login" />
            </div>
          </form>
        </div>
      </div>
    </div>
    <div class="col-md-4">

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

</body>
</html>

<script>
$(document).ready(function(){
  $('#teacher_login_form').on('submit', function(event){
    event.preventDefault();
    $.ajax({
      url:"check_teacher_login.php",
      method:"POST",
      data:$(this).serialize(),
      dataType:"json",
      beforeSend:function()
      {
        $('#teacher_login').val('Validate...');
        $('#teacher_login').attr('disabled', 'disabled');
      },
      success:function(data)
      {
        if(data.success)
        {
          location.href = "index.php";
        }
        if(data.error)
        {
          $('#teacher_login').val('Login');
          $('#teacher_login').attr('disabled', false);
          if(data.error_teacher_emailid != '')
          {
            $('#error_teacher_emailid').text(data.error_teacher_emailid);
          }
          else
          {
            $('#error_teacher_emailid').text('');
          }
          if(data.error_teacher_password != '')
          {
            $('#error_teacher_password').text(data.error_teacher_password);
          }
          else
          {
            $('#error_teacher_password').text('');
          }
        }
      }
    })
  });
});
</script>


check_teacher_login.php



<?php

//check_teacher_login.php

include('admin/database_connection.php');
session_start();
sleep(1);
$teacher_emailid = '';
$teacher_password = '';
$error_teacher_emailid = '';
$error_teacher_password = '';
$error = 0;

if(empty($_POST["teacher_emailid"]))
{
 $error_teacher_emailid = 'Email Address is required';
 $error++;
}
else
{
 $teacher_emailid = $_POST["teacher_emailid"];
}
if(empty($_POST["teacher_password"]))
{
 $error_teacher_password = 'Password is required';
 $error++;
}
else
{
 $teacher_password = $_POST["teacher_password"];
}

if($error == 0)
{
 $query = "
 SELECT * FROM tbl_teacher 
 WHERE teacher_emailid = '".$teacher_emailid."'
 ";
 $statement = $connect->prepare($query);
 if($statement->execute())
 { 
  $total_row = $statement->rowCount();
  if($total_row > 0)
  {
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    if(password_verify($teacher_password, $row["teacher_password"]))
       {
         $_SESSION['teacher_id'] = $row['teacher_id'];
       }
       else
       {
        $error_teacher_password = "Wrong Password";
        $error++;
       }
   }
  }
  else
  {
   $error_teacher_emailid = 'Wrong Email Address';
   $error++;
  }
 }
}

if($error > 0)
{
 $output = array(
  'error'     => true,
  'error_teacher_emailid' => $error_teacher_emailid,
  'error_teacher_password' => $error_teacher_password
 );
}
else
{
 $output = array(
  'success'  => true
 );
}

echo json_encode($output);

?>


header.php



<?php

include('admin/database_connection.php');

session_start();

if(!isset($_SESSION["teacher_id"]))
{
  header("location:login.php");
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Student Attendance System in PHP using Ajax</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <link rel="stylesheet" href="css/dataTables.bootstrap4.min.css">
  <script src="js/jquery.min.js"></script>
  <script src="js/popper.min.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <script src="js/jquery.dataTables.min.js"></script>
  <script src="js/dataTables.bootstrap4.min.js"></script>
</head>
<body>

<div class="jumbotron-small text-center" style="margin-bottom:0">
  <h1>Student Attendance System</h1>
</div>

<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
  <a class="navbar-brand" href="index.php">Home</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="profile.php">Profile</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="attendance.php">Attendance</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="logout.php">Logout</a>
      </li>  
    </ul>
  </div>  
</nav>


index.php



<?php

include('header.php');

?>

<div class="container" style="margin-top:30px">
  <div class="card">
   <div class="card-header">
      <div class="row">
        <div class="col-md-9">Overall Student Attendance Status</div>
        <div class="col-md-3" align="right">
          
        </div>
      </div>
    </div>
   <div class="card-body">
    <div class="table-responsive">
        <span id="message_operation"></span>
     <table class="table table-striped table-bordered" id="student_table">
      <thead>
       <tr>
        <th>Student Name</th>
        <th>Roll Number</th>
        <th>Grade</th>
              <th>Attendance Percentage</th>
              <th>Report</th>
       </tr>
      </thead>
      <tbody>

      </tbody>
     </table>
    </div>
   </div>
  </div>
</div>

</body>
</html>

<script type="text/javascript" src="js/bootstrap-datepicker.js"></script>
<link rel="stylesheet" href="css/datepicker.css" />

<style>
    .datepicker
    {
      z-index: 1600 !important; /* has to be larger than 1050 */
    }
</style>

<div class="modal" id="formModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Make Report</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
        <div class="form-group">
          <div class="input-daterange">
            <input type="text" name="from_date" id="from_date" class="form-control" placeholder="From Date" readonly />
            <span id="error_from_date" class="text-danger"></span>
            <br />
            <input type="text" name="to_date" id="to_date" class="form-control" placeholder="To Date" readonly />
            <span id="error_to_date" class="text-danger"></span>
          </div>
        </div>
      </div>
      <!-- Modal footer -->
      <div class="modal-footer">
        <input type="hidden" name="student_id" id="student_id" />
        <button type="button" name="create_report" id="create_report" class="btn btn-success btn-sm">Create Report</button>
        <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
      </div>

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

<script>
$(document).ready(function(){
 var dataTable = $('#student_table').DataTable({
  "processing":true,
  "serverSide":true,
  "order":[],
  "ajax":{
   url:"attendance_action.php",
   type:"POST",
   data:{action:'index_fetch'}
  }
 });

  $('.input-daterange').datepicker({
    todayBtn: "linked",
    format: "yyyy-mm-dd",
    autoclose: true,
    container: '#formModal modal-body'
  });

  $(document).on('click', '.report_button', function(){
    var student_id = $(this).attr('id');
    $('#student_id').val(student_id);
    $('#formModal').modal('show');
  });

  $('#create_report').click(function(){
    var student_id = $('#student_id').val();
    var from_date = $('#from_date').val();
    var to_date = $('#to_date').val();
    var error = 0;
    if(from_date == '')
    {
      $('#error_from_date').text('From Date is Required');
      error++;
    }
    else
    {
      $('#error_from_date').text('');
    }
    if(to_date == '')
    {
      $('#error_to_date').text('To Date is Required');
      error++;
    }
    else
    {
      $('#error_to_date').text('');
    }
    if(error == 0)
    {
      $('#from_date').val('');
      $('#to_date').val('');
      $('#formModal').modal('hide');
      window.open("report.php?action=student_report&student_id="+student_id+"&from_date="+from_date+"&to_date="+to_date);
    }
  });

});
</script>


logout.php



<?php

//logout.php

session_start();

session_destroy();

header('location:login.php');

?>


Teacher Profile


profile.php



<?php

//profile.php

include('header.php');

$teacher_name = '';
$teacher_address = '';
$teacher_emailid = '';
$teacher_password = '';
$teacher_grade_id = '';
$teacher_qualification = '';
$teacher_doj = '';
$teacher_image = '';
$error_teacher_name = '';
$error_teacher_address = '';
$error_teacher_emailid = '';
$error_teacher_grade_id = '';
$error_teacher_qualification = '';
$error_teacher_doj = '';
$error_teacher_image = '';
$error = 0;
$success = '';

if(isset($_POST["button_action"]))
{
  $teacher_image = $_POST["hidden_teacher_image"];
  if($_FILES["teacher_image"]["name"] != '')
  {
    $file_name = $_FILES["teacher_image"]["name"];
    $tmp_name = $_FILES["teacher_image"]['tmp_name'];
    $extension_array = explode(".", $file_name);
    $extension = strtolower($extension_array[1]);
    $allowed_extension = array('jpg','png');
    if(!in_array($extension, $allowed_extension))
    {
      $error_teacher_image = 'Invalid Image Format';
      $error++;
    }
    else
    {
      $teacher_image = uniqid() . '.' . $extension;
      $upload_path = 'admin/teacher_image/' . $teacher_image;       
      move_uploaded_file($tmp_name, $upload_path);
    } 
  }

  if(empty($_POST["teacher_name"]))
  {
    $error_teacher_name = 'Teacher Name is required';
    $error++;
  }
  else
  {
    $teacher_name = $_POST["teacher_name"];
  }
  if(empty($_POST["teacher_address"]))
  {
    $error_teacher_address = 'Teacher Address is required';
    $error++;
  }
  else
  {
    $teacher_address = $_POST["teacher_address"];
  }
  if(empty($_POST["teacher_emailid"]))
  {
    $error_teacher_emailid = 'Email Address is required';
    $error++;
  }
  else
  {
    if (!filter_var($_POST["teacher_emailid"], FILTER_VALIDATE_EMAIL))
    {
      $error_teacher_emailid = "Invalid email format"; 
      $error++;
    }
    else
    {
      $teacher_emailid = $_POST["teacher_emailid"];
    }
  }
      
  if(!empty($_POST["teacher_password"]))
  {
    $teacher_password = $_POST["teacher_password"];
  }

  if(empty($_POST["teacher_grade_id"]))
  {
    $error_teacher_grade_id = 'Grade is required';
    $error++;
  }
  else
  {
    $teacher_grade_id = $_POST["teacher_grade_id"];
  }

  if(empty($_POST["teacher_qualification"]))
  {
    $error_teacher_qualification = 'Qualification Field is required';
    $error++;
  }
  else
  {
    $teacher_qualification = $_POST["teacher_qualification"];
  }
  if(empty($_POST["teacher_doj"]))
  {
    $error_teacher_doj = 'Date of Join Field is required';
    $error++;
  }
  else
  {
    $teacher_doj = $_POST["teacher_doj"];
  }
  if($error == 0)
  {
    if($teacher_password != "")
    {
      $data = array(
        ':teacher_name'           =>  $teacher_name,
        ':teacher_address'        =>  $teacher_address,
        ':teacher_emailid'        =>  $teacher_emailid,
        ':teacher_password'       =>  password_hash($teacher_password, PASSWORD_DEFAULT),
        ':teacher_qualification'  =>  $teacher_qualification,
        ':teacher_doj'            =>  $teacher_doj,
        ':teacher_image'          =>  $teacher_image,
        ':teacher_grade_id'       =>  $teacher_grade_id,
        ':teacher_id'             =>  $_POST["teacher_id"]
      );

      $query = "
      UPDATE tbl_teacher 
      SET teacher_name = :teacher_name, 
      teacher_address = :teacher_address, 
      teacher_emailid = :teacher_emailid, 
      teacher_password = :teacher_password, 
      teacher_grade_id = :teacher_grade_id, 
      teacher_qualification = :teacher_qualification, 
      teacher_doj = :teacher_doj, 
      teacher_image = :teacher_image 
      WHERE teacher_id = :teacher_id
      ";

    }
    else
    {
      $data = array(
        ':teacher_name'           =>  $teacher_name,
        ':teacher_address'        =>  $teacher_address,
        ':teacher_emailid'        =>  $teacher_emailid,
        ':teacher_qualification'  =>  $teacher_qualification,
        ':teacher_doj'            =>  $teacher_doj,
        ':teacher_image'          =>  $teacher_image,
        ':teacher_grade_id'       =>  $teacher_grade_id,
        ':teacher_id'             =>  $_POST["teacher_id"]
      );
      $query = "
      UPDATE tbl_teacher 
      SET teacher_name = :teacher_name, 
      teacher_address = :teacher_address, 
      teacher_emailid = :teacher_emailid, 
      teacher_grade_id = :teacher_grade_id, 
      teacher_qualification = :teacher_qualification, 
      teacher_doj = :teacher_doj, 
      teacher_image = :teacher_image 
      WHERE teacher_id = :teacher_id
      ";
    }

    $statement = $connect->prepare($query);
    if($statement->execute($data))
    {
      $success = '<div class="alert alert-success">Profile Details Change Successfully</div>';
    }
  }
}

$query = "
SELECT * FROM tbl_teacher 
WHERE teacher_id = '".$_SESSION["teacher_id"]."'
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();

?>

<div class="container" style="margin-top:30px">
  <span id="message_operation"><?php echo $success; ?></span>
  <div class="card">
    <form method="post" id="profile_form" enctype="multipart/form-data">
     <div class="card-header">
        <div class="row">
          <div class="col-md-9">Profile</div>
          <div class="col-md-3" align="right">
            
          </div>
        </div>
      </div>
     <div class="card-body">
      <div class="form-group">
          <div class="row">
            <label class="col-md-4 text-right">Teacher Name <span class="text-danger">*</span></label>
            <div class="col-md-8">
              <input type="text" name="teacher_name" id="teacher_name" class="form-control" />
              <span class="text-danger"><?php echo $error_teacher_name; ?></span>
            </div>
          </div>
        </div>
        <div class="form-group">
          <div class="row">
            <label class="col-md-4 text-right">Address <span class="text-danger">*</span></label>
            <div class="col-md-8">
              <textarea name="teacher_address" id="teacher_address" class="form-control"></textarea>
              <span class="text-danger"><?php echo $error_teacher_address; ?></span>
            </div>
          </div>
        </div>
        <div class="form-group">
          <div class="row">
            <label class="col-md-4 text-right">Email Address <span class="text-danger">*</span></label>
            <div class="col-md-8">
              <input type="text" name="teacher_emailid" id="teacher_emailid" class="form-control" />
              <span class="text-danger"><?php echo $error_teacher_emailid; ?></span>
            </div>
          </div>
        </div>
        <div class="form-group">
          <div class="row">
            <label class="col-md-4 text-right">Password <span class="text-danger">*</span></label>
            <div class="col-md-8">
              <input type="password" name="teacher_password" id="teacher_password" class="form-control" placeholder="Leave blank to not change it" />
              <span class="text-danger"></span>
            </div>
          </div>
        </div>
        <div class="form-group">
          <div class="row">
            <label class="col-md-4 text-right">Qualification <span class="text-danger">*</span></label>
            <div class="col-md-8">
              <input type="text" name="teacher_qualification" id="teacher_qualification" class="form-control" />
              <span class="text-danger"><?php echo $error_teacher_qualification; ?></span>
            </div>
          </div>
        </div>
        <div class="form-group">
          <div class="row">
            <label class="col-md-4 text-right">Grade <span class="text-danger">*</span></label>
            <div class="col-md-8">
              <select name="teacher_grade_id" id="teacher_grade_id" class="form-control">
                <option value="">Select Grade</option>
                <?php
                echo load_grade_list($connect);
                ?>
              </select>
              <span class="text-danger"><?php echo $error_teacher_grade_id; ?></span>
            </div>
          </div>
        </div>
        <div class="form-group">
          <div class="row">
            <label class="col-md-4 text-right">Date of Joining <span class="text-danger">*</span></label>
            <div class="col-md-8">
              <input type="text" name="teacher_doj" id="teacher_doj" class="form-control" readonly />
              <span class="text-danger"><?php echo $error_teacher_doj; ?></span>
            </div>
          </div>
        </div>
        <div class="form-group">
          <div class="row">
            <label class="col-md-4 text-right">Image <span class="text-danger">*</span></label>
            <div class="col-md-8">
              <input type="file" name="teacher_image" id="teacher_image" />
              <span class="text-muted">Only .jpg and .png allowed</span><br />
              <span id="error_teacher_image" class="text-danger"><?php echo $error_teacher_image; ?></span>
            </div>
          </div>
        </div>
     </div>
      <div class="card-footer" align="center">
        <input type="hidden" name="hidden_teacher_image" id="hidden_teacher_image" value="" />
        <input type="hidden" name="teacher_id" id="teacher_id" />
        <input type="submit" name="button_action" id="button_action" class="btn btn-success btn-sm" value="Save" />
      </div>
    </form>
  </div>
</div>

</body>
</html>

<script type="text/javascript" src="js/bootstrap-datepicker.js"></script>
<link rel="stylesheet" href="css/datepicker.css" />

<style>
    .datepicker
    {
      z-index: 1600 !important; /* has to be larger than 1050 */
    }
</style>

<script>
$(document).ready(function(){
 
<?php
foreach($result as $row)
{
?>
$('#teacher_name').val("<?php echo $row['teacher_name']; ?>");
$('#teacher_address').val("<?php echo $row['teacher_address']; ?>");
$('#teacher_emailid').val("<?php echo $row['teacher_emailid']; ?>");
$('#teacher_qualification').val("<?php echo $row['teacher_qualification']; ?>");
$('#teacher_grade_id').val("<?php echo $row['teacher_grade_id']; ?>");
$('#teacher_doj').val("<?php echo $row['teacher_doj']; ?>");
$('#error_teacher_image').html("<img src='admin/teacher_image/<?php echo $row['teacher_image']; ?>' class='img-thumbnail' width='100' />");
$('#hidden_teacher_image').val("<?php echo $row['teacher_image']; ?>");
$('#teacher_id').val("<?php echo $row['teacher_id']; ?>");
<?php
}
?>
  $('#teacher_doj').datepicker({
    format: "yyyy-mm-dd",
    autoclose: true
  });

});
</script>


Attendance Management

attendance.php



<?php

include('header.php');

?>

<div class="container" style="margin-top:30px">
  <div class="card">
   <div class="card-header">
      <div class="row">
        <div class="col-md-9">Attendance List</div>
        <div class="col-md-3" align="right">
          <button type="button" id="report_button" class="btn btn-danger btn-sm">Report</button>
          <button type="button" id="add_button" class="btn btn-info btn-sm">Add</button>
        </div>
      </div>
    </div>
   <div class="card-body">
    <div class="table-responsive">
        <span id="message_operation"></span>
     <table class="table table-striped table-bordered" id="attendance_table">
      <thead>
       <tr>
        <th>Student Name</th>
        <th>Roll Number</th>
        <th>Grade</th>
              <th>Attendance Status</th>
              <th>Attendance Date</th>
       </tr>
      </thead>
      <tbody>

      </tbody>
     </table>
    </div>
   </div>
  </div>
</div>

</body>
</html>

<script type="text/javascript" src="js/bootstrap-datepicker.js"></script>
<link rel="stylesheet" href="css/datepicker.css" />

<style>
    .datepicker
    {
      z-index: 1600 !important; /* has to be larger than 1050 */
    }
</style>

<?php
  $query = "
  SELECT * FROM tbl_grade WHERE grade_id = (SELECT teacher_grade_id FROM tbl_teacher 
    WHERE teacher_id = '".$_SESSION["teacher_id"]."')
  ";
  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();

?>
<div class="modal" id="formModal">
  <div class="modal-dialog">
    <form method="post" id="attendance_form">
      <div class="modal-content">

        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title" id="modal_title"></h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>

        <!-- Modal body -->
        <div class="modal-body">
          <?php
          foreach($result as $row)
          {
          ?>
          <div class="form-group">
            <div class="row">
              <label class="col-md-4 text-right">Grade <span class="text-danger">*</span></label>
              <div class="col-md-8">
                <?php 
                echo '<label>'.$row["grade_name"].'</label>';
                ?>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row">
              <label class="col-md-4 text-right">Attendance Date <span class="text-danger">*</span></label>
              <div class="col-md-8">
                <input type="text" name="attendance_date" id="attendance_date" class="form-control" readonly />
                <span id="error_attendance_date" class="text-danger"></span>
              </div>
            </div>
          </div>
          <div class="form-group" id="student_details">
            <div class="table-responsive">
              <table class="table table-striped table-bordered">
                <thead>
                  <tr>
                    <th>Roll No.</th>
                    <th>Student Name</th>
                    <th>Present</th>
                    <th>Absent</th>
                  </tr>
                </thead>
          <?php
          $sub_query = "
          SELECT * FROM tbl_student 
          WHERE student_grade_id = '".$row["grade_id"]."'
          ";
          $statement = $connect->prepare($sub_query);
          $statement->execute();
          $student_result = $statement->fetchAll();
          foreach($student_result as $student)
          {
          ?>
                <tr>
                  <td><?php echo $student["student_roll_number"]; ?></td>
                  <td>
                    <?php echo $student["student_name"]; ?>
                    <input type="hidden" name="student_id[]" value="<?php echo $student["student_id"]; ?>" />
                  </td>
                  <td align="center">
                    <input type="radio" name="attendance_status<?php echo $student["student_id"]; ?>" value="Present" />
                  </td>
                  <td align="center">
                    <input type="radio" name="attendance_status<?php echo $student["student_id"]; ?>" checked value="Absent" />
                  </td>
                </tr>
          <?php
          }
          ?>
              </table>
            </div>
          </div>
          <?php
          }
          ?>
        </div>

        <!-- Modal footer -->
        <div class="modal-footer">
          <input type="hidden" name="attendance_id" id="attendance_id" />
          <input type="hidden" name="action" id="action" value="Add" />
          <input type="submit" name="button_action" id="button_action" class="btn btn-success btn-sm" value="Add" />
          <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
        </div>

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

<div class="modal" id="reportModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Make Report</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
        <div class="form-group">
          <div class="input-daterange">
            <input type="text" name="from_date" id="from_date" class="form-control" placeholder="From Date" readonly />
            <span id="error_from_date" class="text-danger"></span>
            <br />
            <input type="text" name="to_date" id="to_date" class="form-control" placeholder="To Date" readonly />
            <span id="error_to_date" class="text-danger"></span>
          </div>
        </div>
      </div>
      <!-- Modal footer -->
      <div class="modal-footer">
        <input type="hidden" name="student_id" id="student_id" />
        <button type="button" name="create_report" id="create_report" class="btn btn-success btn-sm">Create Report</button>
        <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
      </div>

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

<script>
$(document).ready(function(){
 var dataTable = $('#attendance_table').DataTable({
  "processing":true,
  "serverSide":true,
  "order":[],
  "ajax":{
   url:"attendance_action.php",
   type:"POST",
   data:{action:'fetch'}
  }
 });

  $('#attendance_date').datepicker({
        format: "yyyy-mm-dd",
        autoclose: true,
        container: '#formModal modal-body'
    });

  function clear_field()
  {
    $('#attendance_form')[0].reset();
    //$('#error_student_grade_id').text('');
    $('#error_attendance_date').text('');
  }

  $('#add_button').click(function(){
    $('#modal_title').text("Add Attendance");
    //$('#button_action').val('Add');
    //$('#action').val('Add');
    $('#formModal').modal('show');
    clear_field();
  });

  



  $('#attendance_form').on('submit', function(event){
    event.preventDefault();
    $.ajax({
      url:"attendance_action.php",
      method:"POST",
      data:$(this).serialize(),
      dataType:"json",
      beforeSend:function()
      {
        $('#button_action').attr('disabled', 'disabled');
        $('#button_action').val('Validate...');
      },
      success:function(data){
        $('#button_action').attr('disabled', false);
        $('#button_action').val($('#action').val());
        if(data.success)
        {
          $('#message_operation').html('<div class="alert alert-success">'+data.success+'</div>');
          clear_field();
          $('#formModal').modal('hide');
          dataTable.ajax.reload();
        }
        if(data.error)
        { 
          if(data.error_attendance_date != '')
          {
            $('#error_attendance_date').text(data.error_attendance_date);
          }
          else
          {
            $('#error_attendance_date').text('');
          }
        }
      }
    });
  });

  $('.input-daterange').datepicker({
    todayBtn: "linked",
    format: "yyyy-mm-dd",
    autoclose: true,
    container: '#formModal modal-body'
  });

  $(document).on('click', '#report_button', function(){
    $('#reportModal').modal('show');
  });

  $('#create_report').click(function(){
    var from_date = $('#from_date').val();
    var to_date = $('#to_date').val();
    var error = 0;
    if(from_date == '')
    {
      $('#error_from_date').text('From Date is Required');
      error++;
    }
    else
    {
      $('#error_from_date').text('');
    }
    if(to_date == '')
    {
      $('#error_to_date').text('To Date is Required');
      error++;
    }
    else
    {
      $('#error_to_date').text('');
    }
    if(error == 0)
    {
      $('#from_date').val('');
      $('#to_date').val('');
      $('#formModal').modal('hide');
      window.open("report.php?action=attendance_report&from_date="+from_date+"&to_date="+to_date);
    }
  });

});
</script>


attendance_action.php



<?php

//attendance_action.php

include('admin/database_connection.php');
session_start();
$output = '';
if(isset($_POST["action"]))
{
 if($_POST["action"] == 'fetch')
 {
  $query = "
  SELECT * FROM tbl_attendance 
  INNER JOIN tbl_student 
  ON tbl_student.student_id = tbl_attendance.student_id 
  INNER JOIN tbl_grade 
  ON tbl_grade.grade_id = tbl_student.student_grade_id 
  WHERE tbl_attendance.teacher_id = '".$_SESSION["teacher_id"]."' AND (";
  if(isset($_POST["search"]["value"]))
  {
   $query .= 'tbl_student.student_name LIKE "%'.$_POST["search"]["value"].'%" 
      OR tbl_student.student_roll_number LIKE "%'.$_POST["search"]["value"].'%" 
      OR tbl_attendance.attendance_status LIKE "%'.$_POST["search"]["value"].'%" 
      OR tbl_attendance.attendance_date LIKE "%'.$_POST["search"]["value"].'%") ';
  }
  if(isset($_POST["order"]))
  {
   $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
  }
  else
  {
   $query .= 'ORDER BY tbl_attendance.attendance_id DESC ';
  }
  if($_POST["length"] != -1)
  {
   $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
  }

  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  $data = array();
  $filtered_rows = $statement->rowCount();
  foreach($result as $row)
  {
   $sub_array = array();
   $status = '';
   if($row["attendance_status"] == 'Present')
   {
    $status = '<label class="badge badge-success">Present</label>';
   }
   if($row["attendance_status"] == 'Absent')
   {
    $status = '<label class="badge badge-danger">Absent</label>';
   }
   
   $sub_array[] = $row["student_name"];
   $sub_array[] = $row["student_roll_number"];
   $sub_array[] = $row["grade_name"];
   $sub_array[] = $status;
   $sub_array[] = $row["attendance_date"];
   $data[] = $sub_array;
  }

  $output = array(
   "draw"    => intval($_POST["draw"]),
   "recordsTotal"  =>  $filtered_rows,
   "recordsFiltered" => get_total_records($connect, 'tbl_attendance'),
   "data"    => $data
  );
  echo json_encode($output);
 }
 if($_POST["action"] == "Add")
 {
  $attendance_date = '';
  $error_attendance_date = '';
  $error = 0;
  if(empty($_POST["attendance_date"]))
  {
   $error_attendance_date = 'Attendance Date is required';
   $error++;
  }
  else
  {
   $attendance_date = $_POST["attendance_date"];
  }
  if($error > 0)
  {
   $output = array(
    'error'       => true,
    'error_attendance_date'   => $error_attendance_date
   );
  }
  else
  {
   $student_id = $_POST["student_id"];
   $query = '
   SELECT attendance_date FROM tbl_attendance 
   WHERE teacher_id = "'.$_SESSION["teacher_id"].'" 
   AND attendance_date = "'.$attendance_date.'"
   ';
   $statement = $connect->prepare($query);
   $statement->execute();
   if($statement->rowCount() > 0)
   {
    $output = array(
     'error'     => true,
     'error_attendance_date' => 'Attendance Data Already Exists on this date'
    );
   }
   else
   {
    for($count = 0; $count < count($student_id); $count++)
    {
     $data = array(
      ':student_id'   => $student_id[$count],
      ':attendance_status' => $_POST["attendance_status".$student_id[$count].""],
      ':attendance_date'  => $attendance_date,
      ':teacher_id'   => $_SESSION["teacher_id"]
     );

     $query = "
     INSERT INTO tbl_attendance 
     (student_id, attendance_status, attendance_date, teacher_id) 
     VALUES (:student_id, :attendance_status, :attendance_date, :teacher_id)
     ";
     $statement = $connect->prepare($query);
     $statement->execute($data);
    }
    $output = array(
     'success'  => 'Data Added Successfully',
    );
   }
  }
  echo json_encode($output);
 }

 if($_POST["action"] == "index_fetch")
 {
  $query = "
  SELECT * FROM tbl_attendance 
  INNER JOIN tbl_student 
  ON tbl_student.student_id = tbl_attendance.student_id 
  INNER JOIN tbl_grade 
  ON tbl_grade.grade_id = tbl_student.student_grade_id 
  WHERE tbl_attendance.teacher_id = '".$_SESSION["teacher_id"]."' AND (";
  if(isset($_POST["search"]["value"]))
  {
   $query .= 'tbl_student.student_name LIKE "%'.$_POST["search"]["value"].'%" 
      OR tbl_student.student_roll_number LIKE "%'.$_POST["search"]["value"].'%" 
      OR tbl_grade.grade_name LIKE "%'.$_POST["search"]["value"].'%" )';
  }

  $query .= 'GROUP BY tbl_student.student_id ';
  if(isset($_POST["order"]))
  {
   $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
  }
  else
  {
   $query .= 'ORDER BY tbl_student.student_roll_number ASC ';
  }

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

  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  $data = array();
  $filtered_rows = $statement->rowCount();
  foreach($result as $row)
  {
   $sub_array = array();
   $sub_array[] = $row["student_name"];
   $sub_array[] = $row["student_roll_number"];
   $sub_array[] = $row["grade_name"];
   $sub_array[] = get_attendance_percentage($connect, $row["student_id"]);
   $sub_array[] = '<button type="button" name="report_button" id="'.$row["student_id"].'" class="btn btn-info btn-sm report_button">Report</button>';
   $data[] = $sub_array;
  }

  $output = array(
   "draw"    => intval($_POST["draw"]),
   "recordsTotal"  =>  $filtered_rows,
   "recordsFiltered" => get_total_records($connect, 'tbl_student'),
   "data"    => $data
  );
  echo json_encode($output);  
 }
}



?>


report.php



<?php

//report.php
if(isset($_GET["action"]))
{
 include('admin/database_connection.php');
 require_once 'admin/pdf.php';
 session_start();
 $output = '';
 if($_GET["action"] == "student_report")
 {
  if(isset($_GET["student_id"], $_GET["from_date"], $_GET["to_date"]))
  {   
   $pdf = new Pdf();
   $query = "
   SELECT * FROM tbl_student 
   INNER JOIN tbl_grade 
   ON tbl_grade.grade_id = tbl_student.student_grade_id 
   WHERE tbl_student.student_id = '".$_GET["student_id"]."' 
   ";
   $statement = $connect->prepare($query);
   $statement->execute();
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    $output .= '
    <style>
    @page { margin: 20px; }
    
    </style>
    <p>&nbsp;</p>
    <h3 align="center">Attendance Report</h3><br /><br />
    <table width="100%" border="0" cellpadding="5" cellspacing="0">
           <tr>
               <td width="25%"><b>Student Name</b></td>
               <td width="75%">'.$row["student_name"].'</td>
           </tr>
           <tr>
               <td width="25%"><b>Roll Number</b></td>
               <td width="75%">'.$row["student_roll_number"].'</td>
           </tr>
           <tr>
               <td width="25%"><b>Grade</b></td>
               <td width="75%">'.$row["grade_name"].'</td>
           </tr>
           <tr>
            <td colspan="2" height="5">
             <h3 align="center">Attendance Details</h3>
            </td>
           </tr>
           <tr>
            <td colspan="2">
             <table width="100%" border="1" cellpadding="5" cellspacing="0">
              <tr>
               <td><b>Attendance Date</b></td>
               <td><b>Attendance Status</b></td>
              </tr>
    ';
    $sub_query = "
    SELECT * FROM tbl_attendance 
    WHERE student_id = '".$_GET["student_id"]."' 
    AND (attendance_date BETWEEN '".$_GET["from_date"]."' AND '".$_GET["to_date"]."') 
    ORDER BY attendance_date ASC
    ";
    $statement = $connect->prepare($sub_query);
    $statement->execute();
    $sub_result = $statement->fetchAll();
    foreach($sub_result as $sub_row)
    {
     $output .= '
      <tr>
       <td>'.$sub_row["attendance_date"].'</td>
       <td>'.$sub_row["attendance_status"].'</td>
      </tr>
     ';
    }
    $output .= '
      </table>
     </td>
     </tr>
    </table>
    ';
    $file_name = 'Attendance Report.pdf';
    $pdf->loadHtml($output);
    $pdf->render();
    $pdf->stream($file_name, array("Attachment" => false));
    exit(0);
   }
  }
 }

 if($_GET["action"] == "attendance_report")
 {
  if(isset($_GET["from_date"], $_GET["to_date"]))
  {
   $pdf = new Pdf();
   $query = "
   SELECT attendance_date FROM tbl_attendance 
   WHERE teacher_id = '".$_SESSION["teacher_id"]."' 
   AND (attendance_date BETWEEN '".$_GET["from_date"]."' AND '".$_GET["to_date"]."')
   GROUP BY attendance_date 
   ORDER BY attendance_date ASC
   ";
   $statement = $connect->prepare($query);
   $statement->execute();
   $result = $statement->fetchAll();
   $output .= '
    <style>
    @page { margin: 20px; }
    
    </style>
    <p>&nbsp;</p>
    <h3 align="center">Attendance Report</h3><br />';
   foreach($result as $row)
   {
    $output .= '
    <table width="100%" border="0" cellpadding="5" cellspacing="0">
           <tr>
            <td><b>Date - '.$row["attendance_date"].'</b></td>
           </tr>
           <tr>
            <td>
             <table width="100%" border="1" cellpadding="5" cellspacing="0">
              <tr>
               <td><b>Student Name</b></td>
               <td><b>Roll Number</b></td>
               <td><b>Grade</b></td>
               <td><b>Attendance Status</b></td>
              </tr>
       ';
       $sub_query = "
       SELECT * FROM tbl_attendance 
       INNER JOIN tbl_student 
       ON tbl_student.student_id = tbl_attendance.student_id 
       INNER JOIN tbl_grade 
       ON tbl_grade.grade_id = tbl_student.student_grade_id 
       WHERE teacher_id = '".$_SESSION["teacher_id"]."' 
    AND attendance_date = '".$row["attendance_date"]."'
       ";
       $statement = $connect->prepare($sub_query);
    $statement->execute();
    $sub_result = $statement->fetchAll();
    foreach($sub_result as $sub_row)
    {
     $output .= '
     <tr>
      <td>'.$sub_row["student_name"].'</td>
      <td>'.$sub_row["student_roll_number"].'</td>
      <td>'.$sub_row["grade_name"].'</td>
      <td>'.$sub_row["attendance_status"].'</td>
     </tr>
     ';
    }
    $output .= 
     '</table>
     </td>
     </tr>
    </table><br />';
   }
   $file_name = 'Attendance Report.pdf';
   $pdf->loadHtml($output);
   $pdf->render();
   $pdf->stream($file_name, array("Attachment" => false));
   exit(0);
  }
 }
}

?>


Admin Side - Attendance Management


admin/attendance.php



<?php

include('header.php');

?>

<div class="container" style="margin-top:30px">
  <div class="card">
   <div class="card-header">
      <div class="row">
        <div class="col-md-9">Attendance List</div>
        <div class="col-md-3" align="right">
          <button type="button" id="report_button" class="btn btn-danger btn-sm">Report</button>
        </div>
      </div>
    </div>
   <div class="card-body">
    <div class="table-responsive">
        <span id="message_operation"></span>
     <table class="table table-striped table-bordered" id="attendance_table">
      <thead>
       <tr>
        <th>Student Name</th>
        <th>Roll Number</th>
        <th>Grade</th>
              <th>Attendance Status</th>
              <th>Attendance Date</th>
        <th>Teacher</th>
       </tr>
      </thead>
      <tbody>

      </tbody>
     </table>
    </div>
   </div>
  </div>
</div>

</body>
</html>

<script type="text/javascript" src="../js/bootstrap-datepicker.js"></script>
<link rel="stylesheet" href="../css/datepicker.css" />

<style>
    .datepicker
    {
      z-index: 1600 !important; /* has to be larger than 1050 */
    }
</style>

<div class="modal" id="reportModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Make Report</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
        <div class="form-group">
          <select name="grade_id" id="grade_id" class="form-control">
            <option value="">Select Grade</option>
            <?php
            echo load_grade_list($connect);
            ?>
          </select>
          <span id="error_grade_id" class="text-danger"></span>
        </div>
        <div class="form-group">
          <div class="input-daterange">
            <input type="text" name="from_date" id="from_date" class="form-control" placeholder="From Date" readonly />
            <span id="error_from_date" class="text-danger"></span>
            <br />
            <input type="text" name="to_date" id="to_date" class="form-control" placeholder="To Date" readonly />
            <span id="error_to_date" class="text-danger"></span>
          </div>
        </div>
      </div>
      <!-- Modal footer -->
      <div class="modal-footer">
        <input type="hidden" name="student_id" id="student_id" />
        <button type="button" name="create_report" id="create_report" class="btn btn-success btn-sm">Create Report</button>
        <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
      </div>

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

<script>
$(document).ready(function(){
 var dataTable = $('#attendance_table').DataTable({
  "processing":true,
  "serverSide":true,
  "order":[],
  "ajax":{
   url:"attendance_action.php",
   type:"POST",
   data:{action:'fetch'}
  }
 });

  $('.input-daterange').datepicker({
    todayBtn: "linked",
    format: "yyyy-mm-dd",
    autoclose: true,
    container: '#formModal modal-body'
  });

  $(document).on('click', '#report_button', function(){
    $('#reportModal').modal('show');
  });

  $('#create_report').click(function(){
    var grade_id = $('#grade_id').val();
    var from_date = $('#from_date').val();
    var to_date = $('#to_date').val();
    var error = 0;
    if(grade_id == '')
    {
      $('#error_grade_id').text('Grade is Required');
      error++;
    }
    else
    {
      $('#error_grade_id').text('');
    }
    if(from_date == '')
    {
      $('#error_from_date').text('From Date is Required');
      error++;
    }
    else
    {
      $('#error_from_date').text('');
    }
    if(to_date == '')
    {
      $('#error_to_date').text('To Date is Required');
      error++;
    }
    else
    {
      $('#error_to_date').text('');
    }
    if(error == 0)
    {
      $('#from_date').val('');
      $('#to_date').val('');
      $('#formModal').modal('hide');
      window.open("report.php?action=attendance_report&grade_id="+grade_id+"&from_date="+from_date+"&to_date="+to_date);
    }
  });

});
</script>


admin/attendance_action.php



<?php

//attendance_action.php

include('database_connection.php');
session_start();
$output = '';
if(isset($_POST["action"]))
{
 if($_POST["action"] == 'fetch')
 {
  $query = "
  SELECT * FROM tbl_attendance 
  INNER JOIN tbl_student 
  ON tbl_student.student_id = tbl_attendance.student_id 
  INNER JOIN tbl_grade 
  ON tbl_grade.grade_id = tbl_student.student_grade_id 
  INNER JOIN tbl_teacher 
  ON tbl_teacher.teacher_id = tbl_attendance.teacher_id ";
  if(isset($_POST["search"]["value"]))
  {
   $query .= 'WHERE tbl_student.student_name LIKE "%'.$_POST["search"]["value"].'%" 
      OR tbl_student.student_roll_number LIKE "%'.$_POST["search"]["value"].'%" 
      OR tbl_attendance.attendance_status LIKE "%'.$_POST["search"]["value"].'%" 
      OR tbl_attendance.attendance_date LIKE "%'.$_POST["search"]["value"].'%" 
      OR tbl_teacher.teacher_name LIKE "%'.$_POST["search"]["value"].'%" ';
  }
  if(isset($_POST["order"]))
  {
   $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
  }
  else
  {
   $query .= 'ORDER BY tbl_attendance.attendance_id DESC ';
  }
  if($_POST["length"] != -1)
  {
   $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
  }

  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  $data = array();
  $filtered_rows = $statement->rowCount();
  foreach($result as $row)
  {
   $sub_array = array();
   $status = '';
   if($row["attendance_status"] == 'Present')
   {
    $status = '<label class="badge badge-success">Present</label>';
   }
   if($row["attendance_status"] == 'Absent')
   {
    $status = '<label class="badge badge-danger">Absent</label>';
   }
   $sub_array[] = $row["student_name"];
   $sub_array[] = $row["student_roll_number"];
   $sub_array[] = $row["grade_name"];
   $sub_array[] = $status;
   $sub_array[] = $row["attendance_date"];
   $sub_array[] = $row["teacher_name"];
   $data[] = $sub_array;
  }

  $output = array(
   "draw"    => intval($_POST["draw"]),
   "recordsTotal"  =>  $filtered_rows,
   "recordsFiltered" => get_total_records($connect, 'tbl_attendance'),
   "data"    => $data
  );
  echo json_encode($output);
 }
}

?>


admin/report.php



<?php

//report.php
if(isset($_GET["action"]))
{
 include('database_connection.php');
 require_once 'pdf.php';
 session_start();
 $output = '';
 if($_GET["action"] == "student_report")
 {
  if(isset($_GET["student_id"], $_GET["from_date"], $_GET["to_date"]))
  {   
   $pdf = new Pdf();
   $query = "
   SELECT * FROM tbl_student 
   INNER JOIN tbl_grade 
   ON tbl_grade.grade_id = tbl_student.student_grade_id 
   WHERE tbl_student.student_id = '".$_GET["student_id"]."' 
   ";
   $statement = $connect->prepare($query);
   $statement->execute();
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    $output .= '
    <style>
    @page { margin: 20px; }
    
    </style>
    <p>&nbsp;</p>
    <h3 align="center">Attendance Report</h3><br /><br />
    <table width="100%" border="0" cellpadding="5" cellspacing="0">
           <tr>
               <td width="25%"><b>Student Name</b></td>
               <td width="75%">'.$row["student_name"].'</td>
           </tr>
           <tr>
               <td width="25%"><b>Roll Number</b></td>
               <td width="75%">'.$row["student_roll_number"].'</td>
           </tr>
           <tr>
               <td width="25%"><b>Grade</b></td>
               <td width="75%">'.$row["grade_name"].'</td>
           </tr>
           <tr>
            <td colspan="2" height="5">
             <h3 align="center">Attendance Details</h3>
            </td>
           </tr>
           <tr>
            <td colspan="2">
             <table width="100%" border="1" cellpadding="5" cellspacing="0">
              <tr>
               <td><b>Attendance Date</b></td>
               <td><b>Attendance Status</b></td>
              </tr>
    ';
    $sub_query = "
    SELECT * FROM tbl_attendance 
    WHERE student_id = '".$_GET["student_id"]."' 
    AND (attendance_date BETWEEN '".$_GET["from_date"]."' AND '".$_GET["to_date"]."') 
    ORDER BY attendance_date ASC
    ";
    $statement = $connect->prepare($sub_query);
    $statement->execute();
    $sub_result = $statement->fetchAll();
    foreach($sub_result as $sub_row)
    {
     $output .= '
      <tr>
       <td>'.$sub_row["attendance_date"].'</td>
       <td>'.$sub_row["attendance_status"].'</td>
      </tr>
     ';
    }
    $output .= '
      </table>
     </td>
     </tr>
    </table>
    ';
    $file_name = 'Attendance Report.pdf';
    $pdf->loadHtml($output);
    $pdf->render();
    $pdf->stream($file_name, array("Attachment" => false));
    exit(0);
   }
  }
 }

 if($_GET["action"] == "attendance_report")
 {
  if(isset($_GET["grade_id"], $_GET["from_date"], $_GET["to_date"]))
  {
   $pdf = new Pdf();
   $query = "
   SELECT tbl_attendance.attendance_date FROM tbl_attendance 
   INNER JOIN tbl_student 
   ON tbl_student.student_id = tbl_attendance.student_id 
   WHERE tbl_student.student_grade_id = '".$_GET["grade_id"]."' 
   AND (tbl_attendance.attendance_date BETWEEN '".$_GET["from_date"]."' AND '".$_GET["to_date"]."')
   GROUP BY tbl_attendance.attendance_date 
   ORDER BY tbl_attendance.attendance_date ASC
   ";
   $statement = $connect->prepare($query);
   $statement->execute();
   $result = $statement->fetchAll();
   $output .= '
    <style>
    @page { margin: 20px; }
    
    </style>
    <p>&nbsp;</p>
    <h3 align="center">Attendance Report</h3><br />';
   foreach($result as $row)
   {
    $output .= '
    <table width="100%" border="0" cellpadding="5" cellspacing="0">
           <tr>
            <td><b>Date - '.$row["attendance_date"].'</b></td>
           </tr>
           <tr>
            <td>
             <table width="100%" border="1" cellpadding="5" cellspacing="0">
              <tr>
               <td><b>Student Name</b></td>
               <td><b>Roll Number</b></td>
               <td><b>Grade</b></td>
               <td><b>Teacher</b></td>
               <td><b>Attendance Status</b></td>
              </tr>
       ';
       $sub_query = "
       SELECT * FROM tbl_attendance 
       INNER JOIN tbl_student 
       ON tbl_student.student_id = tbl_attendance.student_id 
       INNER JOIN tbl_grade 
       ON tbl_grade.grade_id = tbl_student.student_grade_id 
       INNER JOIN tbl_teacher 
       ON tbl_teacher.teacher_grade_id = tbl_grade.grade_id 
       WHERE tbl_student.student_grade_id = '".$_GET["grade_id"]."' 
    AND tbl_attendance.attendance_date = '".$row["attendance_date"]."'
       ";
       $statement = $connect->prepare($sub_query);
    $statement->execute();
    $sub_result = $statement->fetchAll();
    foreach($sub_result as $sub_row)
    {
     $output .= '
     <tr>
      <td>'.$sub_row["student_name"].'</td>
      <td>'.$sub_row["student_roll_number"].'</td>
      <td>'.$sub_row["grade_name"].'</td>
      <td>'.$sub_row["teacher_name"].'</td>
      <td>'.$sub_row["attendance_status"].'</td>
     </tr>
     ';
    }
    $output .= 
     '</table>
     </td>
     </tr>
    </table><br />';
   }
   $file_name = 'Attendance Report.pdf';
   $pdf->loadHtml($output);
   $pdf->render();
   $pdf->stream($file_name, array("Attachment" => false));
   exit(0);
  }
 }
}

?>