Skip to main content

Hospital Management System with PHP & MySQL

Hospital Management System (HMS) is a web application used in hospitals to manage Doctors and Patients. Online Hospital management Systems are used in Hospitals to allow Patients to manage appointments, Doctors can check Patients appointment, view Patients appointment history and Administrator can manage both the Doctors and Patients activities.

So if you’re a developer and thinking to develop your own Hospital Management System, then you’re here at the right place. In our previous tutorial we have explained how to build project management system with PHP and MySQ. In this tutorial you will learn how to develop your own Hospital Management System with PHP and MySQL.

Also, read:

This hospital management system mainly consists of three modules, which are

  • Admin Module
  • Doctor Module
  • Patient Module
Admin Module:
  • Dashboard: In this section, admin can view the Patients, Doctors and Appointments.
  • Doctor: In this section Admin can manage the Doctors to add, edit and delete.
  • Patient: In this section Admin can manage the Patients to add, edit and delete.
  • Appointment: In this section Admin can manage the Appointment to add, edit and delete.
Doctor Module
  • Doctor: In this section Doctor can manage his profile.
  • Patient: In this section Doctor can manage the Patients to add, edit and delete.
  • Appointment: In this section Doctor can view the Appointment.
Patient Module
  • Patient: In this section Patient can manage his profile.
  • Appointment: In this section Patient can manage his Appointment to add, edit and delete.

So let’s implement Hospital Management System with Ajax, PHP and MySQL. The major files are:

  • index.php
  • dashboard.php
  • top_menus.php
  • doctor.php
  • patient.php
  • appointment.php
  • User.php: A class contains users methods.
  • Doctor.php: A class contains methods related to doctor.
  • Patient.php: A class contains methods related to patient.
  • Appointment.php: A class contains methods related to appointment.

Step1: Create MySQL Database Table

First we will create MySQL database tables to develop Hospital system to store Administrators, Doctors, Patients and Appointments details. So we will create table hms_users to store users login details.

CREATE TABLE `hms_users` (
  `id` int(11) UNSIGNED NOT NULL,
  `first_name` varchar(255) DEFAULT NULL,
  `last_name` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `password` varchar(64) NOT NULL,
  `role` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

We will create table hms_doctor to store Doctors details.

CREATE TABLE `hms_doctor` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `address` text NOT NULL,
  `mobile` varchar(255) NOT NULL,
  `fee` int(11) NOT NULL,
  `specialization` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

We will create table hms_patients to store Patients details.

CREATE TABLE `hms_patients` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `gender` varchar(255) NOT NULL,
  `mobile` varchar(255) NOT NULL,
  `address` text NOT NULL,
  `age` int(11) NOT NULL,
  `medical_history` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

We will create table hms_appointments to store Patient appointment details.

CREATE TABLE `hms_appointments` (
  `id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL,
  `specialization_id` int(11) NOT NULL,
  `doctor_id` int(11) NOT NULL,
  `consultancy_fee` int(11) NOT NULL,
  `appointment_date` varchar(255) NOT NULL,
  `appointment_time` varchar(255) NOT NULL,
  `created` datetime NOT NULL DEFAULT current_timestamp(),
  `status` enum('Active','Cancelled','Completed','') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Step2: Manage User Login

We will implement user login functionality to access the system. We will implement login functionality to allow login by administrator, doctor and Patients login to manage system. So in index.php file, we will create login form.

<div class="container-fluid">
	<h2>Example: Hospital Management System with PHP and MySQL</h2>			
	<div class="col-md-6">                    
	<div class="panel panel-info">
		<div class="panel-heading" style="background:#00796B;color:white;">
			<div class="panel-title">Admin Log In</div>                        
		</div> 
		<div style="padding-top:30px" class="panel-body" >
			<?php if ($loginMessage != '') { ?>
				<div id="login-alert" class="alert alert-danger col-sm-12"><?php echo $loginMessage; ?></div>                            
			<?php } ?>
			<form id="loginform" class="form-horizontal" role="form" method="POST" action="">                                    
				<div style="margin-bottom: 25px" class="input-group">
					<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
					<input type="text" class="form-control" id="email" name="email" value="<?php if(!empty($_POST["email"])) { echo $_POST["email"]; } ?>" placeholder="email" style="background:white;" required>                                        
				</div>                                
				<div style="margin-bottom: 25px" class="input-group">
					<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
					<input type="password" class="form-control" id="password" name="password" value="<?php if(!empty($_POST["password"])) { echo $_POST["password"]; } ?>" placeholder="password" required>
				</div>	

				<label class="radio-inline">
				  <input type="radio" name="loginType" value="admin">Administrator
				</label>
				<label class="radio-inline">
				  <input type="radio" name="loginType" value="doctor">Doctor
				</label>
				<label class="radio-inline">
				  <input type="radio" name="loginType" value="patient">Patient
				</label>
				
				<div style="margin-top:10px" class="form-group">                               
					<div class="col-sm-12 controls">
					  <input type="submit" name="login" value="Login" class="btn btn-info">						  
					</div>						
				</div>				
			</form>   
		</div>                     
	</div>  
</div> 

We will handle user login functionality on login form submit. We will call method login() from class User.php.

$loginMessage = '';
if(!empty($_POST["login"]) && !empty($_POST["email"]) && !empty($_POST["password"]) && !empty($_POST["loginType"]) && $_POST["loginType"]) {	
	$user->email = $_POST["email"];
	$user->password = $_POST["password"];	
	$user->loginType = $_POST["loginType"];
	if($user->login()) {
		header("Location: dashboard.php");	
	} else {
		$loginMessage = 'Invalid login! Please try again.';
	}
} else {
	$loginMessage = 'Fill all fields.';
}

We will implement the method login() in class User.php to allow login for Admin, Doctor and Patient to access desired section.

public function login(){
	if($this->email && $this->password) {
		$loginTable = '';
		if($this->loginType == 'admin') {
			$loginTable = "hms_users";
		} else if ($this->loginType == 'doctor') {
			$loginTable = "hms_doctor";
		} else if ($this->loginType == 'patient') {
			$loginTable = "hms_patients";
		}
		$sqlQuery = "
			SELECT * FROM ".$loginTable." 
			WHERE email = ? AND password = ?";			
		$stmt = $this->conn->prepare($sqlQuery);
		$password = md5($this->password);
		$stmt->bind_param("ss", $this->email, $password);	
		$stmt->execute();
		$result = $stmt->get_result();
		if($result->num_rows > 0){
			$user = $result->fetch_assoc();
			$_SESSION["userid"] = $user['id'];
			$_SESSION["role"] = $this->loginType;
			$_SESSION["name"] = $user['email'];					
			return 1;		
		} else {
			return 0;		
		}			
	} else {
		return 0;
	}
}

Step3: Manage Doctors

We will implement functionality to manage Doctors to add edit and delete record. We will create HTML to display Doctors list.

<div> 	
	<div class="panel-heading">
		<div class="row">
			<div class="col-md-10">
				<h3 class="panel-title"></h3>
			</div>
			<div class="col-md-2" align="right">
				<button type="button" id="addDoctor" class="btn btn-info" title="Add Doctor"><span class="glyphicon glyphicon-plus"></span></button>
			</div>
		</div>
	</div>
	<table id="doctorListing" class="table table-bordered table-striped">
		<thead>
			<tr>
				<th>#</th>
				<th>Name</th>					
				<th>Address</th>					
				<th>Mobile</th>
				<th>Fee</th>
				<th>Specialization</th>	
				<th></th>
				<th></th>	
				<th></th>					
			</tr>
		</thead>
	</table>
</div>

In doctor.js file, we will initialize jQuery DataTable to make Ajax request with action listDoctors to load Doctors list

var doctorRecords = $('#doctorListing').DataTable({
	"lengthChange": false,
	"processing":true,
	"serverSide":true,		
	"bFilter": false,
	'serverMethod': 'post',		
	"order":[],
	"ajax":{
		url:"doctor_action.php",
		type:"POST",
		data:{action:'listDoctors'},
		dataType:"json"
	},
	"columnDefs":[
		{
			"targets":[0, 6, 7, 8],
			"orderable":false,
		},
	],
	"pageLength": 10
});	

In doctor_action.php file, we will check for action listDoctors and call method listDoctors().

$doctor = new Doctor($db);

if(!empty($_POST['action']) && $_POST['action'] == 'listDoctors') {
	$doctor->listDoctors();
}

We will implement method listDoctors() in class Doctor.php to get Doctors list and return as JSON data to load into jQuery DataTable.

public function listDoctors(){
		
	$sqlWhere = '';
	if($_SESSION["role"] == 'doctor') { 
		$sqlWhere = " WHERE id = '".$_SESSION["userid"]."'";
	}	
	
	$sqlQuery = "SELECT * FROM ".$this->doctorTable." $sqlWhere ";
	
	if(!empty($_POST["search"]["value"])){
		$sqlQuery .= ' AND (id LIKE "%'.$_POST["search"]["value"].'%" ';
		$sqlQuery .= ' OR name LIKE "%'.$_POST["search"]["value"].'%" ';			
		$sqlQuery .= ' OR mobile LIKE "%'.$_POST["search"]["value"].'%" ';
		$sqlQuery .= ' OR address LIKE "%'.$_POST["search"]["value"].'%" ';
		$sqlQuery .= ' OR fee LIKE "%'.$_POST["search"]["value"].'%" ';
		$sqlQuery .= ' OR specialization LIKE "%'.$_POST["search"]["value"].'%") ';								
	}
	
	if(!empty($_POST["order"])){
		$sqlQuery .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
	} else {
		$sqlQuery .= 'ORDER BY id DESC ';
	}
	
	if($_POST["length"] != -1){
		$sqlQuery .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
	}
	
	$stmt = $this->conn->prepare($sqlQuery);
	$stmt->execute();
	$result = $stmt->get_result();	
	
	$stmtTotal = $this->conn->prepare("SELECT * FROM ".$this->doctorTable." $sqlWhere " );
	$stmtTotal->execute();
	$allResult = $stmtTotal->get_result();
	$allRecords = $allResult->num_rows;
	
	$displayRecords = $result->num_rows;
	$records = array();		
	while ($doctor = $result->fetch_assoc()) { 				
		$rows = array();			
		$rows[] = $doctor['id'];
		$rows[] = ucfirst($doctor['name']);
		$rows[] = $doctor['address'];		
		$rows[] = $doctor['mobile'];	
		$rows[] = $doctor['fee'];	
		$rows[] = $doctor['specialization'];						
		$rows[] = '<button type="button" name="view" id="'.$doctor["id"].'" class="btn btn-info btn-xs view"><span class="glyphicon glyphicon-file" title="View"></span></button>';			
		$rows[] = '<button type="button" name="update" id="'.$doctor["id"].'" class="btn btn-warning btn-xs update"><span class="glyphicon glyphicon-edit" title="Edit"></span></button>';
		$rows[] = '<button type="button" name="delete" id="'.$doctor["id"].'" class="btn btn-danger btn-xs delete" ><span class="glyphicon glyphicon-remove" title="Delete"></span></button>';
		$records[] = $rows;
	}
	
	$output = array(
		"draw"	=>	intval($_POST["draw"]),			
		"iTotalRecords"	=> 	$displayRecords,
		"iTotalDisplayRecords"	=>  $allRecords,
		"data"	=> 	$records
	);
	
	echo json_encode($output);
}

We will implement functionality to insert new Doctor records. So we will implement method insert() in class Doctor.php.

public function insert(){
	
	if($this->name) {

		$stmt = $this->conn->prepare("
		INSERT INTO ".$this->doctorTable."(`name`, `email`, `mobile`, `address`, `fee`,`specialization`,`password`)
		VALUES(?,?,?,?,?,?,?)");
	
		$this->name = htmlspecialchars(strip_tags($this->name));
		$this->email = htmlspecialchars(strip_tags($this->email));
		$this->mobile = htmlspecialchars(strip_tags($this->mobile));
		$this->address = htmlspecialchars(strip_tags($this->address));	
		$this->fee = htmlspecialchars(strip_tags($this->fee));	
		$this->specialization = htmlspecialchars(strip_tags($this->specialization));
		$this->password = md5($this->password);				
		
		$stmt->bind_param("ssssiss", $this->name, $this->email, $this->mobile, $this->address, $this->fee, $this->specialization, $this->password);
		
		if($stmt->execute()){
			return true;
		}		
	}
}

We will also implement method update() method in class Doctor.php

public function update(){
		
	if($this->id) {		
		$passwordField = '';
		if($this->password){
			$passwordField = ", password = '".md5($this->password)."'";
		}
		
		$stmt = $this->conn->prepare("
			UPDATE ".$this->doctorTable." 
			SET name= ?, email = ?, mobile = ?, address = ?, fee = ?, specialization = ? $passwordField
			WHERE id = ?");
 
		$this->id = htmlspecialchars(strip_tags($this->id));
		$this->name = htmlspecialchars(strip_tags($this->name));
		$this->email = htmlspecialchars(strip_tags($this->email));
		$this->mobile = htmlspecialchars(strip_tags($this->mobile));
		$this->address = htmlspecialchars(strip_tags($this->address));	
		$this->fee = htmlspecialchars(strip_tags($this->fee));	
		$this->specialization = htmlspecialchars(strip_tags($this->specialization));			
		
		$stmt->bind_param("ssssisi", $this->name, $this->email, $this->mobile, $this->address, $this->fee, $this->specialization, $this->id);
		
		if($stmt->execute()){
			return true;
		}
		
	}	
}	

Step4: Manage Patients

We will implement functionality to add, edit and delete patients records. We will create HTML to display patient listing.

<div> 	
	<div class="panel-heading">
		<div class="row">
			<div class="col-md-10">
				<h3 class="panel-title"></h3>
			</div>
			<?php if($_SESSION["role"] != 'patient') { ?>
			<div class="col-md-2" align="right">
				<button type="button" id="addPatient" class="btn btn-info" title="Add Patient"><span class="glyphicon glyphicon-plus"></span></button>
			</div>
			<?php } ?>
		</div>
	</div>
	<table id="patientListing" class="table table-bordered table-striped">
		<thead>
			<tr>
				<th>#</th>
				<th>Name</th>					
				<th>Gender</th>	
				<th>Age</th>	
				<th>Email</th>
				<th>Mobile</th>
				<th>Address</th>
				<th>Medical History</th>
				<th></th>
				<th></th>	
				<th></th>					
			</tr>
		</thead>
	</table>
</div>

We will initialize the jQuery DataTable and make ajax with action listPatient to patient_action.php to load patients listing.

var patientRecords = $('#patientListing').DataTable({
	"lengthChange": false,
	"processing":true,
	"serverSide":true,		
	"bFilter": false,
	'serverMethod': 'post',		
	"order":[],
	"ajax":{
		url:"patient_action.php",
		type:"POST",
		data:{action:'listPatient'},
		dataType:"json"
	},
	"columnDefs":[
		{
			"targets":[0, 8, 9, 10],
			"orderable":false,
		},
	],
	"pageLength": 10
});	

We will check for action listPatient and call method listPatients() from class Patient.pm.

$patient = new Patient($db);

if(!empty($_POST['action']) && $_POST['action'] == 'listPatient') {
	$patient->listPatients();
}

We will implement the method listPatients() in class Patient.pm and return the patient data as JSON to display.

public function listPatients(){

	$sqlWhere = '';
	if($_SESSION["role"] == 'patient') { 
		$sqlWhere = "WHERE id = '".$_SESSION["userid"]."'";
	}		
	$sqlQuery = "SELECT * FROM ".$this->patientTable." $sqlWhere";
	if(!empty($_POST["search"]["value"])){
		$sqlQuery .= ' AND (name LIKE "%'.$_POST["search"]["value"].'%" ';			
		$sqlQuery .= ' OR email LIKE "%'.$_POST["search"]["value"].'%" ';
		$sqlQuery .= ' OR gender LIKE "%'.$_POST["search"]["value"].'%" ';
		$sqlQuery .= ' OR mobile LIKE "%'.$_POST["search"]["value"].'%" ';
		$sqlQuery .= ' OR address LIKE "%'.$_POST["search"]["value"].'%" ';				
		$sqlQuery .= ' OR age LIKE "%'.$_POST["search"]["value"].'%") ';							
	}
	
	if(!empty($_POST["order"])){
		$sqlQuery .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
	} else {
		$sqlQuery .= 'ORDER BY id DESC ';
	}
	
	if($_POST["length"] != -1){
		$sqlQuery .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
	}
	
	$stmt = $this->conn->prepare($sqlQuery);
	$stmt->execute();
	$result = $stmt->get_result();	
	
	$stmtTotal = $this->conn->prepare("SELECT * FROM ".$this->patientTable." $sqlWhere");
	$stmtTotal->execute();
	$allResult = $stmtTotal->get_result();
	$allRecords = $allResult->num_rows;
	
	$displayRecords = $result->num_rows;
	$records = array();		
	while ($patient = $result->fetch_assoc()) { 				
		$rows = array();			
		$rows[] = $patient['id'];
		$rows[] = ucfirst($patient['name']);
		$rows[] = $patient['gender'];
		$rows[] = $patient['age'];
		$rows[] = $patient['email'];
		$rows[] = $patient['mobile'];	
		$rows[] = $patient['address'];			
		$rows[] = $patient['medical_history'];			
		$rows[] = '<button type="button" name="view" id="'.$patient["id"].'" class="btn btn-info btn-xs view"><span class="glyphicon glyphicon-file" title="View"></span></button>';			
		$rows[] = '<button type="button" name="update" id="'.$patient["id"].'" class="btn btn-warning btn-xs update"><span class="glyphicon glyphicon-edit" title="Edit"></span></button>';
		if($_SESSION["role"] != 'patient') {
			$rows[] = '<button type="button" name="delete" id="'.$patient["id"].'" class="btn btn-danger btn-xs delete" ><span class="glyphicon glyphicon-remove" title="Delete"></span></button>';
		} else {
			$rows[] = '';
		}
		$records[] = $rows;
	}
	
	$output = array(
		"draw"	=>	intval($_POST["draw"]),			
		"iTotalRecords"	=> 	$displayRecords,
		"iTotalDisplayRecords"	=>  $allRecords,
		"data"	=> 	$records
	);
	
	echo json_encode($output);
}

We will add the new patient record with method insert() from class Patient.php

public function insert(){
		
	if($this->name) {

		$stmt = $this->conn->prepare("
		INSERT INTO ".$this->patientTable."(`name`, `email`, `gender`, `mobile`, `address`,`age`,`medical_history`,`password`)
		VALUES(?,?,?,?,?,?,?,?)");
	
		$this->name = htmlspecialchars(strip_tags($this->name));
		$this->email = htmlspecialchars(strip_tags($this->email));
		$this->gender = htmlspecialchars(strip_tags($this->gender));
		$this->mobile = htmlspecialchars(strip_tags($this->mobile));
		$this->address = htmlspecialchars(strip_tags($this->address));
		$this->age = htmlspecialchars(strip_tags($this->age));	
		$this->medical_history = htmlspecialchars(strip_tags($this->medical_history));	
		$this->password = md5($this->password);
		
		$stmt->bind_param("sssssiss", $this->name, $this->email, $this->gender, $this->mobile, $this->address, $this->age, $this->medical_history, $this->password);
		
		if($stmt->execute()){
			return true;
		}		
	}
}

We will also update the patient with method update() from class Patient.php.

public function update(){
		
	if($this->id) {	

		$passwordField = '';
		if($this->password){
			$passwordField = ", password = '".md5($this->password)."'";
		}
		
		$stmt = $this->conn->prepare("
		UPDATE ".$this->patientTable." 
		SET name= ?, email = ?, gender = ?, mobile = ?, address = ?, age = ?, medical_history = ? $passwordField
		WHERE id = ?");
 
		$this->id = htmlspecialchars(strip_tags($this->id));
		$this->name = htmlspecialchars(strip_tags($this->name));
		$this->email = htmlspecialchars(strip_tags($this->email));
		$this->gender = htmlspecialchars(strip_tags($this->gender));
		$this->mobile = htmlspecialchars(strip_tags($this->mobile));
		$this->address = htmlspecialchars(strip_tags($this->address));
		$this->age = htmlspecialchars(strip_tags($this->age));	
		$this->medical_history = htmlspecialchars(strip_tags($this->medical_history));				
		
		$stmt->bind_param("sssssisi", $this->name, $this->email, $this->gender, $this->mobile, $this->address, $this->age, $this->medical_history, $this->id);
		
		if($stmt->execute()){
			return true;
		}
		
	}	
}

Step5: Manage Appointment

We will implement the functionality to allow patients to get Doctor appointment, list appointment, edit and delete appointment. We will create design to list appointment.

<div> 	
	<div class="panel-heading">
		<div class="row">
			<div class="col-md-10">
				<h3 class="panel-title"></h3>
			</div>
			<?php if($_SESSION["role"] == 'patient') { ?>
			<div class="col-md-2" align="right">
				<button type="button" id="createAppointment" class="btn btn-info" title="Create Appointment"><span class="glyphicon glyphicon-plus"></span></button>
			</div>
			<?php } ?>
		</div>
	</div>
	<table id="appointmentListing" class="table table-bordered table-striped">
		<thead>
			<tr>
				<th>#</th>
				<th>Patient</th>
				<th>Doctor</th>					
				<th>Specialization</th>	
				<th>Fee</th>	
				<th>Apointment Time</th>
				<th>Apointment Date</th>
				<th>Status</th>
				<th></th>
				<th></th>	
				<th></th>					
			</tr>
		</thead>
	</table>
</div>

We will make ajax request with action listAppointment to appointment_action.php to list appointment.

var appointmentRecords = $('#appointmentListing').DataTable({
	"lengthChange": false,
	"processing":true,
	"serverSide":true,		
	"bFilter": false,
	'serverMethod': 'post',		
	"order":[],
	"ajax":{
		url:"appointment_action.php",
		type:"POST",
		data:{action:'listAppointment'},
		dataType:"json"
	},
	"columnDefs":[
		{
			"targets":[0, 8, 9, 10],
			"orderable":false,
		},
	],
	"pageLength": 10
});	

We will check for action and call method listAppointment() from class Appointment.php get appointment list.

$appointment = new Appointment($db);

if(!empty($_POST['action']) && $_POST['action'] == 'listAppointment') {
	$appointment->listAppointment();
}

We will implement the method listAppointment() from class Appointment.php and return records as JSON data.

public function listAppointment(){
		
	$sqlWhere = '';
	if($_SESSION["role"] == 'patient') { 
		$sqlWhere = "WHERE a.patient_id = '".$_SESSION["userid"]."'";
	}	
	
	$sqlQuery = "SELECT a.id, d.name as doctor_name, s.specialization, a.consultancy_fee, appointment_date, a.appointment_time, a.created, a.status, p.name as patient_name, p.id as patient_id
		FROM ".$this->appointmentTable." a 
		LEFT JOIN ".$this->doctorTable." d ON a.doctor_id = d.id
		LEFT JOIN ".$this->patientsTable." p ON a.patient_id = p.id
		LEFT JOIN ".$this->specializationTable." s ON a.specialization_id = s.id $sqlWhere ";
		
		
	if(!empty($_POST["search"]["value"])){
		$sqlQuery .= ' AND (a.id LIKE "%'.$_POST["search"]["value"].'%" ';
		$sqlQuery .= ' OR d.name LIKE "%'.$_POST["search"]["value"].'%" ';			
		$sqlQuery .= ' OR s.specialization LIKE "%'.$_POST["search"]["value"].'%" ';
		$sqlQuery .= ' OR a.consultancy_fee LIKE "%'.$_POST["search"]["value"].'%" ';
		$sqlQuery .= ' OR a.appointment_date LIKE "%'.$_POST["search"]["value"].'%" ';
		$sqlQuery .= ' OR a.appointment_time LIKE "%'.$_POST["search"]["value"].'%") ';					
	}
	
	if(!empty($_POST["order"])){
		$sqlQuery .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
	} else {
		$sqlQuery .= 'ORDER BY a.id DESC ';
	}
	
	if($_POST["length"] != -1){
		$sqlQuery .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
	}		
	$stmt = $this->conn->prepare($sqlQuery);
	$stmt->execute();
	$result = $stmt->get_result();	
	
	$stmtTotal = $this->conn->prepare("SELECT * FROM ".$this->appointmentTable." as a $sqlWhere");
	$stmtTotal->execute();
	$allResult = $stmtTotal->get_result();
	$allRecords = $allResult->num_rows;
	
	$displayRecords = $result->num_rows;
	$records = array();		
	while ($appointment = $result->fetch_assoc()) { 				
		$rows = array();			
		$rows[] = $appointment['id'];
		$rows[] = ucfirst($appointment['patient_name']);
		$rows[] = ucfirst($appointment['doctor_name']);
		$rows[] = $appointment['specialization'];
		$rows[] = $appointment['consultancy_fee'];
		$rows[] = $appointment['appointment_time'];
		$rows[] = $appointment['appointment_date'];	
		$rows[] = $appointment['status'];					
		$rows[] = '<button type="button" name="view" id="'.$appointment["id"].'" class="btn btn-info btn-xs view"><span class="glyphicon glyphicon-file" title="View"></span></button>';
		if($_SESSION["role"] == 'admin' || $_SESSION["role"] == 'patient') { 
			$rows[] = '<button type="button" name="update" id="'.$appointment["id"].'" class="btn btn-warning btn-xs update"><span class="glyphicon glyphicon-edit" title="Edit"></span></button>';
			$rows[] = '<button type="button" name="delete" id="'.$appointment["id"].'" class="btn btn-danger btn-xs delete" ><span class="glyphicon glyphicon-remove" title="Delete"></span></button>';
		} else {
			$rows[] = '';
			$rows[] = '';
			$rows[] = '';
		}
		$records[] = $rows;
	}
	
	$output = array(
		"draw"	=>	intval($_POST["draw"]),			
		"iTotalRecords"	=> 	$displayRecords,
		"iTotalDisplayRecords"	=>  $allRecords,
		"data"	=> 	$records
	);
	
	echo json_encode($output);
}

We will implement the method insert() in class Appointment.php to insert new appointment.

public function insert(){
		
	if($this->doctor_id && $this->specialization_id) {

		$stmt = $this->conn->prepare("
		INSERT INTO ".$this->appointmentTable."(`patient_id`, `specialization_id`, `doctor_id`, `consultancy_fee`, `appointment_date`, `appointment_time`,`status`)
		VALUES(?,?,?,?,?,?,?)");			
		
		$this->doctor_id = htmlspecialchars(strip_tags($this->doctor_id));
		$this->specialization_id = htmlspecialchars(strip_tags($this->specialization_id));
		$this->fee = htmlspecialchars(strip_tags($this->fee));
		$this->appointment_date = htmlspecialchars(strip_tags($this->appointment_date));
		$this->appointment_time = htmlspecialchars(strip_tags($this->appointment_time));
		$this->status = htmlspecialchars(strip_tags($this->status));			
		
		$stmt->bind_param("iiiisss", $_SESSION["userid"], $this->specialization_id, $this->doctor_id, $this->fee, $this->appointment_date, $this->appointment_time, $this->status);
		
		if($stmt->execute()){
			return true;
		}		
	}
}		

We will also implement the method update() in class Appointment.php to update the appointment.

public function update(){
		
	if($this->id) {		
		
		$stmt = $this->conn->prepare("
		UPDATE ".$this->appointmentTable." 
		SET patient_id = ?, specialization_id= ?, doctor_id = ?, consultancy_fee = ?, appointment_date = ?, appointment_time = ?, status = ?
		WHERE id = ?");
 
		$this->id = htmlspecialchars(strip_tags($this->id));			
		$this->doctor_id = htmlspecialchars(strip_tags($this->doctor_id));
		$this->specialization_id = htmlspecialchars(strip_tags($this->specialization_id));
		$this->fee = htmlspecialchars(strip_tags($this->fee));
		$this->appointment_date = htmlspecialchars(strip_tags($this->appointment_date));
		$this->appointment_time = htmlspecialchars(strip_tags($this->appointment_time));
		$this->status = htmlspecialchars(strip_tags($this->status));			
		
		$stmt->bind_param("iiiisssi", $_SESSION["userid"], $this->specialization_id, $this->doctor_id, $this->fee, $this->appointment_date, $this->appointment_time, $this->status, $this->id);
		
		if($stmt->execute()){
			return true;
		}
		
	}	
}

Step6: Conclusion

In this tutorial, we have implement Hospital management system with Ajax, PHP and MySQL. We have covered Admin, Doctors, Patients and Appointment section. You can download the project and can customize and enhance according to your requirement.

You may also like:

You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download

14 thoughts on “Hospital Management System with PHP & MySQL

  1. Hi!
    Your work is amazing and very helpful!
    Thank you so much for sharing it! 🙂
    I am trying to make it work on my localhost but I cant log in..could you please help me?
    I have follow your steps, I had create a user in the DB in order to login with his credentials but is not possible.

    Thank you in advance!

      1. Hi! Thank you very much for all you do and share with us.
        Thow too lite, i appreciate a lot your tuto.
        For the admin part, would you please tell me where can I find the update so I can complete this session.

        THKX

  2. Login for role patient and doctor is not working in the project “show message Fill all fields.”

      1. HOWZIT, SO THANK YOU GREAT TUTORIAL.
        ALL THOUGH STRUGGLING WITH ONE THING AFTER I SET UP THE DB AND INSERT LOGIN INFORMATION IF DOES NOT WORK?

    1. Login for doctor and patients aren’t opening it shows fill all fields. Should I insert the values into the tables in the database?

Comments are closed.