based on this codes index.php (<?php
// longeva_health_journey_answers/index.php
// Start session and include necessary files
session_start();
require '../db_connect.php';
// Check if the user is logged in as admin
if (!isset($_SESSION['admin_id'])) {
header("Location: ../login.php"); // Redirect to login page
exit();
}
// Include the header
include '../includes/header.php';
// Initialize variables
$patients = [];
try {
// Fetch all patients who completed the page 8 survey
// Including additional tables via LEFT JOIN
$sql = "
SELECT
pbi.patient_id,
pbi.name AS patient_name,
pbi.email AS patient_email,
pbi.phone AS patient_phone,
pbi.gender AS patient_gender,
pbi.age AS patient_age,
pbi.weight AS patient_weight,
pbi.height AS patient_height,
pbi.created_at,
pbi.updated_at,
pc.scheduled_at,
cons.consent,
goals.primary_health_goals,
goals.health_concerns,
metrics.exercise_frequency,
metrics.diet,
metrics.diet_specify,
metrics.sleep_average,
metrics.smoking_status,
history.chronic_conditions,
history.chronic_conditions_specify,
history.medications,
history.medications_list,
history.major_surgeries,
history.major_surgeries_specify
FROM
patient_basic_info pbi
INNER JOIN
patient_consultation pc ON pbi.patient_id = pc.patient_id
LEFT JOIN
patient_consent cons ON pbi.patient_id = cons.patient_id
LEFT JOIN
patient_goals goals ON pbi.patient_id = goals.patient_id
LEFT JOIN
patient_health_metrics metrics ON pbi.patient_id = metrics.patient_id
LEFT JOIN
patient_medical_history history ON pbi.patient_id = history.patient_id
";
// Function to fetch patients for dropdown
function fetch_all_patients(pdo) {
sql = "SELECT id, name, email FROM patients ORDER BY name ASC";
stmt=pdo->prepare(sql);stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
try {
if (patient_id > 0) {
// Fetch existing patient data
sql = "
SELECT
p.id AS patient_id,
p.name AS patient_name,
p.email AS patient_email,
p.phone AS patient_phone,
p.gender AS patient_gender,
p.age AS patient_age,
p.address AS patient_address,
pbi.weight AS patient_weight,
pbi.height AS patient_height,
pc.scheduled_at
FROM
patients p
LEFT JOIN
patient_basic_info pbi ON p.id = pbi.patient_id
LEFT JOIN
patient_consultation pc ON p.id = pc.patient_id
WHERE
p.id = ?
";
code
$stmt = $pdo->prepare($sql);
$stmt->execute([$patient_id]);
$patient = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$patient) {
$errors[] = "Patient not found.";
}
}
// Handle form submission
if (_SERVER['REQUEST_METHOD'] === 'POST') {
// Determine if patient is selected via dropdown or pre-filled
if (isset(_POST['patient_id']) && _POST['patient_id'] > 0) {
patient_id = intval($_POST['patient_id']);
}
// Prepare SQL statement
sql="SELECTa.∗,p.packagenameFROMappointmentsaLEFTJOINpackagespONa.packageid=p.idwhere_sql
ORDER BY a.appointment_date ASC
";
-- Host: 127.0.0.1:3306
-- Generation Time: Oct 17, 2024 at 03:42 AM
-- Server version: 10.11.9-MariaDB
-- PHP Version: 7.2.34
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 appointments
CREATE TABLE appointments (
id int(11) NOT NULL,
package_id int(11) NOT NULL,
appointment_date datetime NOT NULL,
proposed_appointment_date datetime DEFAULT NULL,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL,
phone varchar(20) NOT NULL,
age int(3) DEFAULT NULL,
gender enum('Male','Female','Other') DEFAULT NULL,
address varchar(255) DEFAULT NULL,
preferred_contact_method enum('Email','Phone','WhatsApp') DEFAULT NULL,
additional_notes text DEFAULT NULL,
admin_notes text DEFAULT NULL,
status enum('Pending','Confirmed','Completed','Cancelled') DEFAULT 'Pending',
created_at timestamp NULL DEFAULT current_timestamp(),
patient_id int(11) 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,
is_online tinyint(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table expenses
CREATE TABLE expenses (
id int(11) NOT NULL,
expense_date date NOT NULL,
category varchar(100) NOT NULL,
description varchar(255) DEFAULT NULL,
amount decimal(10,2) NOT 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;
--
-- 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(),
due_date date DEFAULT NULL,
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 packages
CREATE TABLE packages (
id int(11) NOT NULL,
package_name varchar(255) NOT NULL,
description text DEFAULT NULL,
details text DEFAULT NULL,
created_at timestamp NULL DEFAULT current_timestamp()
) 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(3) DEFAULT NULL,
gender enum('Male','Female','Other') DEFAULT 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,
address varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table patient_basic_info
CREATE TABLE patient_basic_info (
patient_id int(11) NOT NULL,
gender enum('Male','Female','Other') NOT NULL,
age int(3) NOT NULL,
weight decimal(5,2) NOT NULL,
height decimal(5,2) NOT NULL,
name varchar(100) NOT NULL,
email varchar(100) NOT NULL,
phone varchar(20) NOT 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;
--
-- Table structure for table patient_consent
CREATE TABLE patient_consent (
patient_id int(11) NOT NULL,
consent enum('accepted','declined') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table patient_consultation
CREATE TABLE patient_consultation (
patient_id int(11) NOT NULL,
scheduled_at datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table patient_goals
CREATE TABLE patient_goals (
patient_id int(11) NOT NULL,
primary_health_goals text NOT NULL,
health_concerns text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table patient_health_metrics
CREATE TABLE patient_health_metrics (
patient_id int(11) NOT NULL,
exercise_frequency enum('Daily','Weekly','Rarely','Never') NOT NULL,
diet enum('Yes','No') NOT NULL,
diet_specify varchar(255) DEFAULT NULL,
sleep_average enum('<5 Hours','5-7 Hours','7-9 Hours','>9 Hours') NOT NULL,
smoking_status enum('Yes','No','Occasionally') NOT 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 patient_medical_history
CREATE TABLE patient_medical_history (
patient_id int(11) NOT NULL,
chronic_conditions enum('Yes','No') NOT NULL,
chronic_conditions_specify varchar(255) DEFAULT NULL,
medications enum('Yes','No') NOT NULL,
medications_list text DEFAULT NULL,
major_surgeries enum('Yes','No') NOT NULL,
major_surgeries_specify varchar(255) DEFAULT 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 prescriptions
CREATE TABLE prescriptions (
id int(11) NOT NULL,
patient_id int(11) NOT NULL,
doctor_id int(11) DEFAULT NULL,
medications text NOT NULL,
instructions text DEFAULT NULL,
date_prescribed datetime DEFAULT current_timestamp(),
status enum('active','inactive') DEFAULT 'active'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table questionnaire_responses
CREATE TABLE questionnaire_responses (
id int(11) NOT NULL,
session_id varchar(255) NOT NULL,
page_number int(2) NOT NULL,
question varchar(255) NOT NULL,
answer text NOT NULL,
submitted_at timestamp NULL DEFAULT current_timestamp(),
consent enum('Yes','No') DEFAULT 'No'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_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;
ALTER TABLE invoice_services
ADD CONSTRAINT invoice_services_ibfk_1 FOREIGN KEY (invoice_id) REFERENCES invoices (id) ON DELETE CASCADE,
ADD CONSTRAINT invoice_services_ibfk_2 FOREIGN KEY (service_id) REFERENCES services (service_id) ON DELETE CASCADE;
--
-- Constraints for table patients
ALTER TABLE patients
ADD CONSTRAINT patients_ibfk_1 FOREIGN KEY (doctor_id) REFERENCES doctors (id) ON DELETE SET NULL ON UPDATE CASCADE;
--
-- Constraints for table patient_logins
ALTER TABLE patient_logins
ADD CONSTRAINT patient_logins_ibfk_1 FOREIGN KEY (patient_id) REFERENCES patients (id) ON DELETE CASCADE;
--
-- Constraints for table payments
ALTER TABLE payments
ADD CONSTRAINT payments_ibfk_1 FOREIGN KEY (patient_id) REFERENCES patients (id) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT payments_ibfk_2 FOREIGN KEY (invoice_id) REFERENCES invoices (id) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table prescriptions
ALTER TABLE prescriptions
ADD CONSTRAINT prescriptions_ibfk_1 FOREIGN KEY (patient_id) REFERENCES patients (id) ON DELETE CASCADE,
ADD CONSTRAINT prescriptions_ibfk_2 FOREIGN KEY (doctor_id) REFERENCES doctors (id) ON DELETE SET NULL;
--
-- Constraints for table salaries
ALTER TABLE salaries
ADD CONSTRAINT salaries_ibfk_1 FOREIGN KEY (employee_id) REFERENCES employees (id) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT /;
/!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS /;
/!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;) so make add appointment select from patient_basic_info table to add in manage appoinmtnet page and type full codes with guides and update database and make sure eeveryghins is ok, (i meant add patient_basic_info to appointments table by add_appointment.php)
To integrate the patient_basic_info table seamlessly into your appointment management system, we'll adjust both the Add Appointment and Manage Appointments functionalities. This ensures that appointments are correctly linked to patients' basic information and that all relevant details are displayed appropriately.
Below is a comprehensive guide with updated code snippets and explanations to help you achieve this integration successfully.
1. Updating the add_appointment.php File
a. Fetching Patients from patient_basic_info
Instead of fetching patients from the patients table, we'll retrieve them from the patient_basic_info table. This ensures that appointments are linked to the correct patient information.
b. Ensuring Proper Mapping of patient_id
The patient_id in the appointments table should reference the patient_id from the patient_basic_info table, which in turn corresponds to the id in the patients table.
c. Full Updated Code for add_appointment.php
php
<?php
// appointment/add_appointment.php
session_start();
require_once '../db_connect.php';
// Check if the user is logged in as admin
if (!isset($_SESSION['admin_id'])) {
header("Location: ../login.php"); // Redirect to login page
exit();
}
// Initialize variables
$errors = [];
$success = '';
$patient = [];
// Function to fetch patients from patient_basic_info
function fetch_all_patients_basic_info($pdo) {
$sql = "SELECT pbi.patient_id, pbi.name, pbi.email FROM patient_basic_info pbi ORDER BY pbi.name ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
try {
// If patient_id is provided via GET, fetch their information
if (isset($_GET['patient_id']) && intval($_GET['patient_id']) > 0) {
$patient_id = intval($_GET['patient_id']);
$sql = "
SELECT
p.id AS patient_id,
p.name AS patient_name,
p.email AS patient_email,
p.phone AS patient_phone,
p.gender AS patient_gender,
p.age AS patient_age,
p.address AS patient_address,
pbi.weight AS patient_weight,
pbi.height AS patient_height,
pc.scheduled_at
FROM
patients p
LEFT JOIN
patient_basic_info pbi ON p.id = pbi.patient_id
LEFT JOIN
patient_consultation pc ON p.id = pc.patient_id
WHERE
p.id = ?
";
$stmt = $pdo->prepare($sql);
$stmt->execute([$patient_id]);
$patient = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$patient) {
$errors[] = "Patient not found.";
}
}
} catch (PDOException $e) {
$errors[] = "Database Error: " . htmlspecialchars($e->getMessage());
}
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Determine if patient is selected via dropdown or pre-filled
if (isset($_POST['patient_id']) && $_POST['patient_id'] > 0) {
$patient_id = intval($_POST['patient_id']);
} elseif (isset($_POST['hidden_patient_id']) && $_POST['hidden_patient_id'] > 0) {
$patient_id = intval($_POST['hidden_patient_id']);
} else {
$patient_id = 0;
}
// Collect and sanitize inputs
$appointment_date = isset($_POST['appointment_date']) ? trim($_POST['appointment_date']) : '';
$proposed_appointment_date = isset($_POST['proposed_appointment_date']) && !empty($_POST['proposed_appointment_date']) ? trim($_POST['proposed_appointment_date']) : null;
$status = isset($_POST['status']) ? trim($_POST['status']) : '';
$preferred_contact_method = isset($_POST['preferred_contact_method']) ? trim($_POST['preferred_contact_method']) : '';
$additional_notes = isset($_POST['additional_notes']) ? trim($_POST['additional_notes']) : '';
$admin_notes = isset($_POST['admin_notes']) ? trim($_POST['admin_notes']) : '';
// Validation
if ($patient_id <= 0) {
$errors[] = "Please select a valid patient.";
}
if (empty($appointment_date)) {
$errors[] = "Appointment date and time are required.";
} else {
// Validate datetime format
$date = DateTime::createFromFormat('Y-m-d\TH:i', $appointment_date);
if (!$date) {
$errors[] = "Invalid appointment date and time format.";
} else {
$appointment_date_formatted = $date->format('Y-m-d H:i:s');
}
}
if (!empty($proposed_appointment_date)) {
$proposed_date = DateTime::createFromFormat('Y-m-d\TH:i', $proposed_appointment_date);
if (!$proposed_date) {
$errors[] = "Invalid proposed appointment date and time format.";
} else {
$proposed_appointment_date_formatted = $proposed_date->format('Y-m-d H:i:s');
}
}
if (empty($status)) {
$errors[] = "Appointment status is required.";
} elseif (!in_array($status, ['Pending', 'Confirmed', 'Completed', 'Cancelled'])) {
$errors[] = "Invalid appointment status.";
}
if (empty($preferred_contact_method)) {
$errors[] = "Preferred contact method is required.";
} elseif (!in_array($preferred_contact_method, ['Email','Phone','WhatsApp'])) {
$errors[] = "Invalid contact method.";
}
if (empty($errors)) {
try {
// Begin transaction
$pdo->beginTransaction();
// Optionally, set package_id. Adjust as needed.
// Assuming a default package exists with id=1
$package_id = 1;
// Insert into appointments table
$stmt = $pdo->prepare("
INSERT INTO appointments
(package_id, appointment_date, proposed_appointment_date, status, preferred_contact_method, additional_notes, admin_notes, status, patient_id)
VALUES
(:package_id, :appointment_date, :proposed_appointment_date, :status, :preferred_contact_method, :additional_notes, :admin_notes, :status, :patient_id)
");
$stmt->execute([
':package_id' => $package_id,
':appointment_date' => $appointment_date_formatted,
':proposed_appointment_date' => isset($proposed_appointment_date_formatted) ? $proposed_appointment_date_formatted : null,
':status' => $status,
':preferred_contact_method' => $preferred_contact_method,
':additional_notes' => $additional_notes,
':admin_notes' => $admin_notes,
':status' => $status,
':patient_id' => $patient_id
]);
// Commit transaction
$pdo->commit();
// Redirect to manage appointments with success message
$_SESSION['success_message'] = "Appointment added successfully.";
header("Location: manage_appointments.php");
exit();
} catch (PDOException $e) {
// Rollback transaction on error
$pdo->rollBack();
$errors[] = "Database Error: " . htmlspecialchars($e->getMessage());
}
}
}
// Fetch all patients from patient_basic_info for the dropdown if no patient is pre-selected
$all_patients = [];
if (!isset($patient_id) || $patient_id <= 0) {
$all_patients = fetch_all_patients_basic_info($pdo);
}
// Include the header
include '../includes/header.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Add Appointment - Longeva</title>
<!-- Include Bootstrap CSS and any other required CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"/>
<!-- Custom CSS -->
<style>
/* Custom styles */
body {
background-color: #f8f9fa;
font-family: 'Roboto', sans-serif;
}
.container {
max-width: 800px;
margin-top: 50px;
background-color: #ffffff;
padding: 30px 40px;
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
margin-bottom: 30px;
color: #4F3F02;
}
.btn-primary, .btn-secondary {
border-radius: 50px;
padding: 10px 20px;
margin: 5px;
}
.btn-primary {
background-color: #D1C287;
border-color: #D1C287;
color: #4F3F02;
}
.btn-primary:hover {
background-color: #4F3F02;
color: #ffffff;
}
.btn-secondary {
background-color: #4F3F02;
border-color: #4F3F02;
color: #ffffff;
}
.btn-secondary:hover {
background-color: #D1C287;
color: #4F3F02;
}
.form-section {
margin-bottom: 30px;
}
.form-section h4 {
color: #4F3F02;
margin-bottom: 20px;
border-bottom: 2px solid #D1C287;
padding-bottom: 10px;
}
.alert {
margin-top: 20px;
border-radius: 8px;
}
</style>
</head>
<body>
<div class="container">
<h2>Add New Appointment</h2>
<?php
if (!empty($errors)) {
echo '<div class="alert alert-danger">';
foreach ($errors as $error) {
echo "<p>" . htmlspecialchars($error) . "</p>";
}
echo '</div>';
}
if (!empty($success)) {
echo '<div class="alert alert-success">' . htmlspecialchars($success) . '</div>';
}
?>
<form method="POST" action="">
<!-- Patient Selection (if patient_id not pre-selected) -->
<?php if (!isset($patient_id) || $patient_id <= 0): ?>
<div class="form-section">
<h4>Select Patient</h4>
<div class="form-group">
<label for="patient_id">Patient:<span class="text-danger">*</span></label>
<select id="patient_id" name="patient_id" class="form-control" required>
<option value="">-- Select Patient --</option>
<?php foreach ($all_patients as $pat): ?>
<option value="<?= htmlspecialchars($pat['patient_id']) ?>" <?= (isset($_POST['patient_id']) && $_POST['patient_id'] == $pat['patient_id']) ? 'selected' : '' ?>>
<?= htmlspecialchars($pat['name']) ?> - <?= htmlspecialchars($pat['email']) ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<?php endif; ?>
<!-- Hidden input to retain patient_id if pre-selected -->
<?php if (isset($patient_id) && $patient_id > 0): ?>
<input type="hidden" name="hidden_patient_id" value="<?= htmlspecialchars($patient_id) ?>">
<?php endif; ?>
<!-- Display Patient Information (Read-Only if patient_id is provided) -->
<?php if (isset($patient_id) && $patient_id > 0 && empty($errors)): ?>
<div class="form-section">
<h4>Patient Information</h4>
<div class="form-group">
<label>Full Name:</label>
<input type="text" class="form-control" value="<?= htmlspecialchars($patient['patient_name']) ?>" readonly>
</div>
<div class="form-group">
<label>Email Address:</label>
<input type="email" class="form-control" value="<?= htmlspecialchars($patient['patient_email']) ?>" readonly>
</div>
<div class="form-group">
<label>Phone Number:</label>
<input type="text" class="form-control" value="<?= htmlspecialchars($patient['patient_phone']) ?>" readonly>
</div>
<div class="form-group">
<label>Gender:</label>
<input type="text" class="form-control" value="<?= htmlspecialchars($patient['patient_gender']) ?>" readonly>
</div>
<div class="form-group">
<label>Age:</label>
<input type="number" class="form-control" value="<?= htmlspecialchars($patient['patient_age']) ?>" readonly>
</div>
<div class="form-group">
<label>Address:</label>
<textarea class="form-control" rows="2" readonly><?= htmlspecialchars($patient['patient_address']) ?></textarea>
</div>
</div>
<?php endif; ?>
<!-- Appointment Details -->
<div class="form-section">
<h4>Appointment Details</h4>
<div class="form-group">
<label>Appointment Date & Time:<span class="text-danger">*</span></label>
<input type="datetime-local" name="appointment_date" class="form-control" value="<?= isset($_POST['appointment_date']) ? htmlspecialchars($_POST['appointment_date']) : '' ?>" required>
</div>
<div class="form-group">
<label>Proposed Appointment Date & Time:</label>
<input type="datetime-local" name="proposed_appointment_date" class="form-control" value="<?= isset($_POST['proposed_appointment_date']) ? htmlspecialchars($_POST['proposed_appointment_date']) : '' ?>">
<small class="form-text text-muted">Use this field to propose a new appointment date/time if needed.</small>
</div>
<div class="form-group">
<label>Status:<span class="text-danger">*</span></label>
<select name="status" class="form-control" required>
<option value="">--Select Status--</option>
<option value="Pending" <?= (isset($_POST['status']) && $_POST['status'] === 'Pending') ? 'selected' : '' ?>>Pending</option>
<option value="Confirmed" <?= (isset($_POST['status']) && $_POST['status'] === 'Confirmed') ? 'selected' : '' ?>>Confirmed</option>
<option value="Completed" <?= (isset($_POST['status']) && $_POST['status'] === 'Completed') ? 'selected' : '' ?>>Completed</option>
<option value="Cancelled" <?= (isset($_POST['status']) && $_POST['status'] === 'Cancelled') ? 'selected' : '' ?>>Cancelled</option>
</select>
</div>
<div class="form-group">
<label>Preferred Contact Method:<span class="text-danger">*</span></label>
<select name="preferred_contact_method" class="form-control" required>
<option value="">--Select Contact Method--</option>
<option value="Email" <?= (isset($_POST['preferred_contact_method']) && $_POST['preferred_contact_method'] === 'Email') ? 'selected' : '' ?>>Email</option>
<option value="Phone" <?= (isset($_POST['preferred_contact_method']) && $_POST['preferred_contact_method'] === 'Phone') ? 'selected' : '' ?>>Phone</option>
<option value="WhatsApp" <?= (isset($_POST['preferred_contact_method']) && $_POST['preferred_contact_method'] === 'WhatsApp') ? 'selected' : '' ?>>WhatsApp</option>
</select>
</div>
<div class="form-group">
<label>Additional Notes:</label>
<textarea name="additional_notes" class="form-control" rows="3"><?= isset($_POST['additional_notes']) ? htmlspecialchars($_POST['additional_notes']) : '' ?></textarea>
</div>
<div class="form-group">
<label>Admin Notes:</label>
<textarea name="admin_notes" class="form-control" rows="3"><?= isset($_POST['admin_notes']) ? htmlspecialchars($_POST['admin_notes']) : '' ?></textarea>
<small class="form-text text-muted">Internal notes for administrative purposes.</small>
</div>
</div>
<!-- Action Buttons -->
<div class="form-group text-center">
<button type="submit" class="btn btn-primary">Add Appointment</button>
<a href="manage_appointments.php" class="btn btn-secondary">Cancel</a>
</div>
</form>
</div>
<!-- Include Bootstrap JS and dependencies -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
<?php
// Include the footer
include '../includes/footer.php';
?>
d. Explanation of Changes
Fetching Patients:
Function Update: Changed fetch_all_patients() to fetch_all_patients_basic_info(), which fetches patient_id, name, and email from patient_basic_info.
Dropdown Population: The dropdown now displays patients from patient_basic_info.
Handling Pre-selected Patients:
Hidden Input: If a patient_id is provided via GET (e.g., from index.php), it displays the patient's information and retains the patient_id using a hidden input field.
Form Submission:
Data Insertion: Ensured that the patient_id from patient_basic_info is correctly inserted into the appointments table.
Error Handling & Transactions: Maintained robust error handling with transactions to ensure data integrity.
User Interface:
Read-Only Fields: When a patient is pre-selected, their information is displayed in read-only fields to prevent accidental modifications.
CSS & Layout: Maintained consistent styling for a modern and user-friendly interface.
2. Updating the manage_appointments.php File
a. Integrating patient_basic_info into Appointment Management
To display comprehensive patient information within the appointments table, we'll join the appointments table with the patient_basic_info table. This allows us to show details like the patient's name and email directly alongside their appointments.
b. Full Updated Code for manage_appointments.php
php
c. Explanation of Changes
SQL Query Enhancements:
Join with patient_basic_info: Added a LEFT JOIN with patient_basic_info to fetch name, email, and phone directly from this table.
Additional Join with patients: Ensured that if there are any additional patient details in the patients table, they are also accessible.
Search Functionality:
Search Criteria Update: Modified the search criteria to search within patient_basic_info.name, patient_basic_info.email, and patients.phone.
Table Columns Update:
Added Patient Email and Phone Columns: Included Email and Phone as separate columns in the appointments table for better visibility.
Status Labels:
Consistent Styling: Maintained status labels with color-coded backgrounds to enhance readability.
DataTables Integration:
Enhanced User Experience: Enabled sorting, pagination, and searchable functionalities for the appointments table using DataTables.
Appointment Statistics:
Real-Time Stats: The summary section dynamically displays the count of appointments based on their statuses.
User Interface:
Consistent Styling: Ensured that the layout and styling remain consistent with the rest of the application for a cohesive user experience.
3. Database Integrity and Foreign Key Relations
a. Ensuring Referential Integrity
Given your database schema, make sure that the patient_basic_info.patient_id correctly references patients.id. This is crucial to maintain the integrity of the data.
b. Example Foreign Key Constraint
If not already enforced, you can add a foreign key constraint to ensure that every patient_id in patient_basic_info exists in the patients table:
sql
ALTER TABLE `patient_basic_info`
ADD CONSTRAINT `fk_patient_basic_info_patient` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
Note: Always back up your database before making structural changes.
c. Verifying Existing Constraints
From your provided SQL dump, ensure that all necessary foreign key constraints are in place:
Appointments Table:
patient_id references patients.id
package_id references packages.id
Patient Basic Info Table:
(If not already) patient_id references patients.id
d. Adjusting Other Related Tables
Ensure that any other tables referencing patients.id are correctly linked, such as patient_medical_history, insurance_claims, etc.
4. Final Steps and Verification
a. Testing the Changes
Add an Appointment:
Navigate to the Add Appointment page.
Select a patient from the dropdown (sourced from patient_basic_info).
Fill in the appointment details and submit.
Ensure you're redirected to the Manage Appointments page with a success message.
Manage Appointments:
Verify that the newly added appointment appears in the table with correct patient details.
Test the search and filter functionalities to ensure they work as expected.
Data Integrity:
Check the database to confirm that the appointments table correctly records the patient_id referencing patient_basic_info.
b. Error Handling and Debugging
Debug Mode: Keep error reporting enabled during development for easier debugging. However, disable it in the production environment to prevent sensitive information exposure.
php
// For development
ini_set('display_errors', 1);
error_reporting(E_ALL);
// For production
// ini_set('display_errors', 0);
// error_reporting(0);
Validation: Ensure all form inputs are properly validated and sanitized to prevent SQL injection and other security vulnerabilities.
c. Backup and Deployment
Backup Database: Always back up your database before making changes.
Staging Environment: Test all changes in a staging environment before deploying to production.
Documentation: Document all changes for future reference and maintenance.
5. Conclusion
By updating both the Add Appointment and Manage Appointments functionalities to utilize the patient_basic_info table, you ensure a more organized and accurate association between patients and their appointments. This integration enhances data integrity, improves user experience, and streamlines administrative tasks within your Longeva Health Journey application.
Ensure you thoroughly test all changes in a controlled environment before deploying them to your live application. If you encounter any issues or need further assistance, feel free to ask!