// Check if the admin is logged in
if (!isset($_SESSION['admin_id'])) {
header("Location: ../admin_login.php");
exit();
}
// Initialize variables
error=′′;success = '';
// Handle form submission for assigning a doctor to a patient
if (_SERVER['REQUEST_METHOD'] == 'POST' && isset(_POST['assign_doctor'])) {
_POST['patient_id'] ?? 0);
_POST['doctor_id'] ?? 0);
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
if ($patient_id <= 0 || $doctor_id <= 0) {
$error = "Please select both patient and doctor.";
} else {
try {
// Check if the doctor exists
$stmt = $pdo->prepare("SELECT COUNT(*) FROM doctors WHERE id = ?");
$stmt->execute([$doctor_id]);
if ($stmt->fetchColumn() == 0) {
$error = "Selected doctor does not exist.";
} else {
// Check if the patient exists
$stmt = $pdo->prepare("SELECT COUNT(*) FROM patients WHERE id = ?");
$stmt->execute([$patient_id]);
if ($stmt->fetchColumn() == 0) {
$error = "Selected patient does not exist.";
} else {
// Check if the association already exists
$stmt = $pdo->prepare("SELECT COUNT(*) FROM doctor_patient WHERE doctor_id = ? AND patient_id = ?");
$stmt->execute([$doctor_id, $patient_id]);
if ($stmt->fetchColumn() > 0) {
$error = "This doctor is already assigned to the selected patient.";
} else {
// Assign the doctor to the patient
$stmt = $pdo->prepare("INSERT INTO doctor_patient (doctor_id, patient_id) VALUES (?, ?)");
if ($stmt->execute([$doctor_id, $patient_id])) {
$success = "Doctor assigned to patient successfully.";
} else {
$error = "Failed to assign doctor. Please try again.";
}
}
}
}
} catch (PDOException $e) {
$error = "Database error: " . $e->getMessage();
}
}
}
// Handle removal of a doctor-patient association
if (_SERVER['REQUEST_METHOD'] == 'POST' && isset(_POST['remove_association'])) {
associationid=intval(_POST['association_id'] ?? 0);
if (association_id <= 0) {
error = "Invalid association selected.";
} else {
try {
stmt=pdo->prepare("DELETE FROM doctor_patient WHERE id = ?");
if (stmt−>execute([association_id])) {
success = "Doctor removed from patient successfully.";
} else {
error = "Failed to remove association. Please try again.";
}
} catch (PDOException e) {
error = "Database error: " . $e->getMessage();
}
}
}
// Fetch all doctors for the assign form
doctorsstmt=pdo->prepare("SELECT id, name, specialization FROM doctors ORDER BY name ASC");
doctorsstmt−>execute();doctors = $doctors_stmt->fetchAll(PDO::FETCH_ASSOC);
// Fetch all patients for the assign form
patientsstmt=pdo->prepare("SELECT id, name FROM patients ORDER BY name ASC");
patientsstmt−>execute();patients = $patients_stmt->fetchAll(PDO::FETCH_ASSOC);
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT /;
/!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS /;
/!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION /;
/!40101 SET NAMES utf8mb4 */;
--
-- Database: u406552082_info
--
-- Table structure for table admins
CREATE TABLE admins (
id int(11) NOT NULL,
username varchar(50) NOT NULL,
password varchar(255) NOT NULL,
email varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table budgets
CREATE TABLE budgets (
id int(11) NOT NULL,
month varchar(7) DEFAULT NULL,
budgeted_revenue decimal(10,2) DEFAULT NULL,
budgeted_expenses decimal(10,2) DEFAULT NULL,
notes text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table comments
CREATE TABLE comments (
id int(11) NOT NULL,
patient_id int(11) NOT NULL,
sender enum('patient','doctor','admin') NOT NULL,
message text NOT NULL,
timestamp datetime DEFAULT current_timestamp(),
parent_id int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table doctors
CREATE TABLE doctors (
id int(11) NOT NULL,
employee_id int(11) NOT NULL,
name varchar(255) NOT NULL,
username varchar(100) NOT NULL,
password varchar(255) NOT NULL,
email varchar(255) NOT NULL,
specialization varchar(255) DEFAULT NULL,
phone varchar(20) DEFAULT NULL,
registration_date date DEFAULT curdate(),
profile_picture varchar(255) DEFAULT NULL,
department varchar(100) DEFAULT NULL,
date_of_joining date DEFAULT NULL,
status enum('active','inactive') DEFAULT 'active'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table doctor_patient
CREATE TABLE doctor_patient (
id int(11) NOT NULL,
doctor_id int(11) NOT NULL,
patient_id int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table employees
CREATE TABLE employees (
id int(11) NOT NULL,
name varchar(255) NOT NULL,
role enum('admin','doctor','staff','accountant') NOT NULL,
email varchar(255) NOT NULL,
phone varchar(20) DEFAULT NULL,
department varchar(100) DEFAULT NULL,
date_of_joining date DEFAULT NULL,
status enum('active','inactive') DEFAULT 'active',
username varchar(100) NOT NULL,
password varchar(255) NOT NULL,
created_at timestamp NULL DEFAULT current_timestamp(),
updated_at timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
profile_picture varchar(255) DEFAULT NULL,
specialization varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table health_records
CREATE TABLE health_records (
id int(11) NOT NULL,
patient_id int(11) NOT NULL,
blood_pressure varchar(20) DEFAULT NULL,
weight decimal(5,2) DEFAULT NULL,
bmi decimal(4,2) DEFAULT NULL,
cholesterol decimal(5,2) DEFAULT NULL,
prescription text DEFAULT NULL,
treatment_progress text DEFAULT NULL,
record_date date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table insurance_claims
CREATE TABLE insurance_claims (
id int(11) NOT NULL,
patient_id int(11) DEFAULT NULL,
invoice_id int(11) DEFAULT NULL,
claim_amount decimal(10,2) DEFAULT NULL,
status enum('Pending','Approved','Rejected') DEFAULT NULL,
submission_date date DEFAULT NULL,
processing_date date DEFAULT NULL,
notes text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table invoices
CREATE TABLE invoices (
id int(11) NOT NULL,
patient_id int(11) NOT NULL,
service_name varchar(255) NOT NULL,
service_description text DEFAULT NULL,
cost decimal(10,2) NOT NULL,
tax_rate decimal(5,2) DEFAULT 0.00,
discount decimal(5,2) DEFAULT 0.00,
total_amount decimal(10,2) NOT NULL,
invoice_date date DEFAULT curdate(),
notes text DEFAULT NULL,
tax decimal(5,2) DEFAULT 0.00
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table invoice_services
CREATE TABLE invoice_services (
id int(11) NOT NULL,
invoice_id int(11) NOT NULL,
service_id int(11) NOT NULL,
service_name varchar(255) NOT NULL,
cost decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table patients
CREATE TABLE patients (
id int(11) NOT NULL,
name varchar(100) NOT NULL,
age int(11) NOT NULL,
gender enum('Male','Female','Other') NOT NULL,
phone varchar(20) DEFAULT NULL,
email varchar(100) DEFAULT NULL,
medical_history text DEFAULT NULL,
created_at timestamp NULL DEFAULT current_timestamp(),
updated_at timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
date_of_birth date DEFAULT NULL,
registration_datetime datetime DEFAULT current_timestamp(),
registration_date date DEFAULT NULL,
status enum('Initial Consultation','Diagnostic Phase','Treatment in Progress','Improving','Monitoring','Maintenance Phase','Awaiting Test Results','Follow-up Needed','Paused','Completed Program','Relapsed','Discontinued','Inactive') DEFAULT 'Initial Consultation',
doctor_id int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table patient_logins
CREATE TABLE patient_logins (
id int(11) NOT NULL,
patient_id int(11) NOT NULL,
username varchar(50) NOT NULL,
password varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table payments
CREATE TABLE payments (
id int(11) NOT NULL,
patient_id int(11) NOT NULL,
invoice_id int(11) NOT NULL,
amount_paid decimal(10,2) NOT NULL,
payment_date date NOT NULL,
payment_method varchar(50) DEFAULT NULL,
notes text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table salaries
CREATE TABLE salaries (
id int(11) NOT NULL,
employee_id int(11) NOT NULL,
basic_salary decimal(10,2) NOT NULL,
bonuses decimal(10,2) DEFAULT 0.00,
deductions decimal(10,2) DEFAULT 0.00,
overtime_hours int(11) DEFAULT 0,
overtime_rate decimal(10,2) DEFAULT 0.00,
tax decimal(10,2) DEFAULT 0.00,
payment_date date NOT NULL,
net_salary decimal(10,2) NOT NULL,
status enum('Pending','Paid') DEFAULT 'Pending',
notes text DEFAULT NULL,
payslip_path varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table services
CREATE TABLE services (
service_id int(11) NOT NULL,
service_name varchar(255) NOT NULL,
service_price decimal(10,2) NOT NULL,
service_description text DEFAULT NULL,
created_at timestamp NULL DEFAULT current_timestamp(),
updated_at timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Certainly! To enhance the usability of your manage_doctors.php script and make it suitable for managing a large number of patients, we can implement several improvements:
Implement Patient Search Instead of Dropdown:
Issue: Using a dropdown menu to select patients becomes impractical when there are many patients.
Solution: Replace the patient dropdown with an autocomplete search field that allows the admin to type in the patient's name or ID, and fetch matching results dynamically.
Use AJAX for Dynamic Data Loading:
Implement AJAX calls to fetch patient data as the admin types into the search field. This avoids loading all patient data at once and improves performance.
Similarly, you can implement this for doctors if the number of doctors is large.
Follow MVC Architecture:
Separate your code into Models (database interactions), Views (HTML templates), and Controllers (business logic). This enhances code maintainability and readability.
Use Prepared Statements and Handle Exceptions:
Ensure all database interactions use prepared statements to prevent SQL injection.
Properly catch exceptions and provide user-friendly error messages.
Improve User Interface:
Enhance the UI to be more responsive and user-friendly.
Use modals or separate pages for assigning doctors, removing associations, etc.
Pagination for Current Assignments:
If there are many doctor-patient assignments, implement pagination to make the list manageable.
Add Features:
Bulk Assignments: Allow admins to assign doctors to multiple patients at once.
Filter and Sorting: Provide filtering options to search assignments by doctor, patient, or other criteria.
Export Data: Allow exporting assignments to CSV or Excel for reporting purposes.
Optimize Database Queries:
Index relevant columns (if not already indexed) to improve query performance.
Use JOINs efficiently to fetch necessary data.
Implement CSRF Protection:
Use tokens to protect against Cross-Site Request Forgery attacks.
Form Validation:
Use both client-side (JavaScript) and server-side validation to ensure data integrity.
Implementation Steps:
Below, I'll guide you through implementing an autocomplete search for patients using AJAX, which is crucial for handling large datasets.
Step 1: Create an Endpoint to Fetch Patients (fetch_patients.php)
Create a new PHP script that queries patients based on search input.
<?php
// fetch_patients.php
session_start();
require_once '../db_connect.php';
// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
http_response_code(403);
echo json_encode(['error' => 'Unauthorized']);
exit;
}
$searchTerm = $_GET['term'] ?? '';
if ($searchTerm) {
try {
$stmt = $pdo->prepare("SELECT id, name FROM patients WHERE name LIKE ? ORDER BY name ASC LIMIT 10");
$stmt->execute(["%{$searchTerm}%"]);
$patients = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($patients);
} catch (PDOException $e) {
http_response_code(500);
echo json_encode(['error' => 'Database error']);
}
} else {
echo json_encode([]);
}
?>
Security Measures:
Checks if the admin is logged in.
Uses prepared statements to prevent SQL injection.
Limits results to 10 to reduce load.
Step 2: Modify the HTML Form
Replace the patient dropdown with an input field that utilizes autocomplete.
The autocomplete widget sends the term parameter to fetch_patients.php.
The server responds with a JSON array of patients matching the search term.
When a patient is selected, their ID is stored in the hidden patient_id field.
Step 4: Update Form Submission Handling
Ensure that the patient_id is obtained from the hidden input when the form is submitted.
// In manage_doctors.php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['assign_doctor'])) {
$patient_id = intval($_POST['patient_id'] ?? 0);
$doctor_id = intval($_POST['doctor_id'] ?? 0);
if ($patient_id <= 0 || $doctor_id <= 0) {
$error = "Please select both patient and doctor.";
} else {
// Proceed with the assignment logic as before
}
}
Note: Ensure that the form uses the correct method="post" and that all inputs have the correct name attributes.
Step 5: Secure the AJAX Endpoint
Ensure that only authorized users can access fetch_patients.php by checking if the admin is logged in.
Already implemented in fetch_patients.php with the session check.
Additional Improvements:
1. Implement CSRF Tokens:
Add a hidden CSRF token to the form to protect against Cross-Site Request Forgery.
// At the top of manage_doctors.php
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];
<!-- Add to the form -->
<input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
// In form handling
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
$error = "Invalid CSRF token";
// Handle error appropriately
}
2. Server-Side Validation:
Ensure all inputs are validated on the server-side to prevent malicious inputs.
3. Use Prepared Statements for All Queries:
Ensure that all your SQL statements use prepared statements.
4. Enhance the Doctor Selection:
If you also have a large number of doctors, implement a similar autocomplete or filtering mechanism.
Improving the User Interface:
1. Use Modals for Assigning Doctors:
Instead of having the assignment form on the page, you can use a modal popup. This declutters the page and provides a better user experience.
2. Display Selected Patient and Doctor Details:
Once a patient and doctor are selected, display their details below the form to confirm the correct selection.
3. Responsive Design:
Ensure that the page is mobile-friendly by using responsive design techniques.
4. Use DataTables for Assignments Table:
Implement the DataTables plugin to enhance the assignments table with features like search, pagination, and sorting.
Ensure that the patients table has an index on the name column since you're querying it with LIKE.
ALTER TABLE patients ADD INDEX idx_name (name);
Implement Pagination for Current Assignments:
If there are many assignments, paginating them will improve load times and usability.
Adding Bulk Assignment Feature:
Allow admins to assign multiple patients to a doctor at once.
1. Modify the Form:
Use a multiselect input for patients or provide a way to upload a CSV file containing patient IDs.
2. Handle Bulk Assignments in PHP:
Loop through the selected patient IDs and assign each one to the doctor.
Example:
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['assign_doctor'])) {
$doctor_id = intval($_POST['doctor_id'] ?? 0);
$patient_ids = $_POST['patient_ids'] ?? [];
if ($doctor_id <= 0 || empty($patient_ids)) {
$error = "Please select both patient(s) and doctor.";
} else {
// Loop through patient IDs and assign each one
foreach ($patient_ids as $patient_id) {
$patient_id = intval($patient_id);
// Perform assignment logic
}
$success = "Doctor assigned to selected patients successfully.";
}
}
Implementing Logging and Auditing:
Create a log table to record all assignments and removals.
CREATE TABLE assignment_logs (
id INT AUTO_INCREMENT PRIMARY KEY,
admin_id INT NOT NULL,
action VARCHAR(50) NOT NULL,
doctor_id INT NOT NULL,
patient_id INT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (admin_id) REFERENCES admins(id),
FOREIGN KEY (doctor_id) REFERENCES doctors(id),
FOREIGN KEY (patient_id) REFERENCES patients(id)
);
Usage:
Insert a log record each time an assignment or removal is made.
Securing Your Application:
1. Session Management:
Regenerate session IDs upon login to prevent session fixation attacks.
Set appropriate session cookie parameters, like httponly and secure.
2. Input Sanitization:
Use PHP's filter functions to sanitize inputs.
3. Error Handling:
Display user-friendly error messages.
Log technical details to a server log that isn't exposed to the user.
Refactoring to MVC:
Consider organizing your code using the Model-View-Controller (MVC) pattern.
Models: Classes that interact with the database.
Views: Templates that display data to the user.
Controllers: Handle user input and interactions, manipulating models and rendering views.
This separation of concerns makes your codebase more maintainable.
Final Note:
By implementing these improvements, your application will be more user-friendly, scalable, and maintainable. It will be easier to manage large datasets, and your code will adhere to best practices.
If you need assistance with any specific part of this implementation or have questions about other features, feel free to ask!
Remember: Always test new features thoroughly in a development environment before deploying them to production to ensure they work correctly and securely.