// Define status options (Assuming these are the possible statuses)
// Adjust these options based on your actual ENUM values in the database
$status_options = ['Initial Consultation', 'Treatment in Progress', 'Completed', 'Follow-up'];
// Initialize filter variables
search=_GET['search'] ?? '';
genderfilter=_GET['gender'] ?? '';
statusfilter=_GET['status'] ?? '';
sortby=_GET['sort_by'] ?? 'p.name'; // Default sort by patient name
sortorder=_GET['sort_order'] ?? 'ASC'; // Default sort order
// Define allowed columns for sorting to prevent SQL injection
allowedsort=[′p.name′,′sort_by, allowed_sort)) {
sort_by = 'p.name';
}
// Build the SQL query with filters
sql="SELECTp.∗,pl.username,hr.bloodpressure,hrparams = ['doctor_id' => $doctor_id];
// Apply search filter
if (search) {
sql .= " AND (p.name LIKE :search OR pl.username LIKE :search OR p.phone LIKE :search OR p.email LIKE :search)";
params[′search′]="search%";
}
// Apply gender filter
if (gender_filter) {
sql .= " AND p.gender = :gender";
params[′gender′]=gender_filter;
}
// Apply status filter
if (status_filter) {
sql .= " AND p.status = :status";
params[′status′]=status_filter;
}
// Fetch total patients for pagination
$count_sql = "
SELECT COUNT(*)
FROM patients p
LEFT JOIN doctor_patient dp ON p.id = dp.patient_id
LEFT JOIN patient_logins pl ON p.id = pl.patient_id -- Added JOIN to patient_logins
WHERE dp.doctor_id = :doctor_id
";
countparams=[′doctorid′=>doctor_id];
// Apply the same filters to the count query
if (search) {
count_sql .= " AND (p.name LIKE :search OR pl.username LIKE :search OR p.phone LIKE :search OR p.email LIKE :search)";
countparams[′search′]="search%";
}
if (gender_filter) {
count_sql .= " AND p.gender = :gender";
countparams[′gendergender_filter;
}
if (status_filter) {
count_sql .= " AND p.status = :status";
countparams[′statusstatus_filter;
}
// Prepare and execute the final query
stmt=pdo->prepare(sql);foreach(params as key => &value) {
if (key==′limit′∣∣key == 'offset') {
stmt−>bindParam(′:′.key, value, PDO::PARAM_INT);
} else {
stmt->bindParam(':' . key,value, PDO::PARAM_STR);
}
}
stmt−>execute();patients = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Fetch patient status distribution for the pie chart
statusstmt=pdo->prepare("
SELECT p.status, COUNT(*) as count
FROM patients p
JOIN doctor_patient dp ON p.id = dp.patient_id
WHERE dp.doctor_id = :doctor_id
GROUP BY p.status
");
statusstmt−>execute([′doctoridoctor_id]);
statusdata=status_stmt->fetchAll(PDO::FETCH_ASSOC);
// Fetch gender distribution for the histogram
genderstmt=pdo->prepare("
SELECT p.gender, COUNT(*) as count
FROM patients p
JOIN doctor_patient dp ON p.id = dp.patient_id
WHERE dp.doctor_id = :doctor_id
GROUP BY p.gender
");
genderstmt−>execute([′doctoridoctor_id]);
genderdata=gender_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
File Paths
Here are the file paths for the PHP files mentioned in the previous messages:
/your_web_root/
│
├── admin_dashboard.php // Admin dashboard displaying patient list
├── admin_login.php // Admin login page
├── admin_logout.php // Admin logout functionality
├── create_patient.php // Page for creating a new patient
├── view_patient.php // Page for viewing patient details
├── edit_patient.php // Page for editing patient information
├── delete_patient.php // Page for deleting a patient
├── add_health_record.php // Page for adding health records for a patient
├── edit_health_record.php // Page for editing health records
├── patient_login.php // Patient login page
├── patient_dashboard.php // Patient dashboard displaying their information
├── patient_logout.php // Patient logout functionality
├── db_connect.php // Database connection file
├── index.php // index home
├── update_patient_status.php // update patient st
├── doctors/
│ ├── login.php
│ ├── logout.php
│ ├── dashboard.php
│ ├── view_patient.php
│ ├── edit_patient.php
│ ├── add_health_record.php
│ └── health_records.php
├── patients/
│ ├── delete_comment.php
│ ├── patient_dashboard.php
│ ├── patient_login.php
│ ├── send_comment.php
│ ├── patient_logout.php
├── invoice/
│ ├── index.php // Page for generating an invoice
│ ├── services.php // Page for generating a services
│ ├── create_invoice.php
│ ├── edit_invoice.php
│ ├── print_invoice.php
│ ├── view_invoice.php /
)
Certainly! I've updated your dashboard.php code to fix errors, adjust the charts, make the design responsive, and align it with your database structure. The charts are now displayed in one row with two columns using Bootstrap's grid system. I've also refined the CSS to enhance the overall look and feel. Here's the updated code:
<?php
// doctors/dashboard.php
// Enable error reporting for debugging (Disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
require_once '../db_connect.php'; // Ensure the path is correct
// Ensure the doctor is logged in
if (!isset($_SESSION['doctor_id'])) {
header("Location: login.php");
exit();
}
$doctor_id = $_SESSION['doctor_id'];
// Fetch doctor information
$stmt = $pdo->prepare("SELECT * FROM doctors WHERE id = ?");
$stmt->execute([$doctor_id]);
$doctor = $stmt->fetch();
if (!$doctor) {
// Invalid session
session_destroy();
header("Location: login.php");
exit();
}
// Define status options (Adjust these based on your actual ENUM values)
$status_options = ['Initial Consultation', 'Treatment in Progress', 'Completed', 'Follow-up'];
// Initialize filter variables
$search = $_GET['search'] ?? '';
$gender_filter = $_GET['gender'] ?? '';
$status_filter = $_GET['status'] ?? '';
$sort_by = $_GET['sort_by'] ?? 'p.name';
$sort_order = $_GET['sort_order'] ?? 'ASC';
// Define allowed columns for sorting to prevent SQL injection
$allowed_sort = ['p.name', 'p.age', 'p.gender', 'p.status', 'p.registration_datetime'];
if (!in_array($sort_by, $allowed_sort)) {
$sort_by = 'p.name';
}
$sort_order = strtoupper($sort_order) === 'DESC' ? 'DESC' : 'ASC';
// Pagination parameters
$limit = 10; // Number of patients per page
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : 1;
$page = max($page, 1);
$offset = ($page - 1) * $limit;
// Build the SQL query with filters
$sql = "
SELECT p.*, pl.username,
hr.blood_pressure, hr.weight, hr.bmi, hr.cholesterol,
hr.prescription, hr.treatment_progress, hr.record_date
FROM patients p
LEFT JOIN doctor_patient dp ON p.id = dp.patient_id
LEFT JOIN patient_logins pl ON p.id = pl.patient_id
LEFT JOIN (
SELECT hr.*
FROM health_records hr
INNER JOIN (
SELECT patient_id, MAX(record_date) as max_record_date
FROM health_records
GROUP BY patient_id
) latest_hr ON hr.patient_id = latest_hr.patient_id AND hr.record_date = latest_hr.max_record_date
) hr ON p.id = hr.patient_id
WHERE dp.doctor_id = :doctor_id
";
$params = ['doctor_id' => $doctor_id];
// Apply filters
if ($search) {
$sql .= " AND (p.name LIKE :search OR pl.username LIKE :search OR p.phone LIKE :search OR p.email LIKE :search)";
$params['search'] = "%$search%";
}
if ($gender_filter) {
$sql .= " AND p.gender = :gender";
$params['gender'] = $gender_filter;
}
if ($status_filter) {
$sql .= " AND p.status = :status";
$params['status'] = $status_filter;
}
// Fetch total patients for pagination
$count_sql = "
SELECT COUNT(*)
FROM patients p
LEFT JOIN doctor_patient dp ON p.id = dp.patient_id
LEFT JOIN patient_logins pl ON p.id = pl.patient_id
WHERE dp.doctor_id = :doctor_id
";
$count_params = ['doctor_id' => $doctor_id];
// Apply the same filters to the count query
if ($search) {
$count_sql .= " AND (p.name LIKE :search OR pl.username LIKE :search OR p.phone LIKE :search OR p.email LIKE :search)";
$count_params['search'] = "%$search%";
}
if ($gender_filter) {
$count_sql .= " AND p.gender = :gender";
$count_params['gender'] = $gender_filter;
}
if ($status_filter) {
$count_sql .= " AND p.status = :status";
$count_params['status'] = $status_filter;
}
$count_stmt = $pdo->prepare($count_sql);
$count_stmt->execute($count_params);
$total_patients = $count_stmt->fetchColumn();
$total_pages = ceil($total_patients / $limit);
// Apply sorting
$sql .= " ORDER BY $sort_by $sort_order";
// Apply pagination
$sql .= " LIMIT :limit OFFSET :offset";
$params['limit'] = $limit;
$params['offset'] = $offset;
// Prepare and execute the final query
$stmt = $pdo->prepare($sql);
foreach ($params as $key => &$value) {
if ($key == 'limit' || $key == 'offset') {
$stmt->bindParam(':' . $key, $value, PDO::PARAM_INT);
} else {
$stmt->bindParam(':' . $key, $value);
}
}
$stmt->execute();
$patients = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Fetch patient status distribution for the pie chart
$status_stmt = $pdo->prepare("
SELECT p.status, COUNT(*) as count
FROM patients p
JOIN doctor_patient dp ON p.id = dp.patient_id
WHERE dp.doctor_id = :doctor_id
GROUP BY p.status
");
$status_stmt->execute(['doctor_id' => $doctor_id]);
$status_data = $status_stmt->fetchAll(PDO::FETCH_ASSOC);
// Fetch gender distribution for the histogram
$gender_stmt = $pdo->prepare("
SELECT p.gender, COUNT(*) as count
FROM patients p
JOIN doctor_patient dp ON p.id = dp.patient_id
WHERE dp.doctor_id = :doctor_id
GROUP BY p.gender
");
$gender_stmt->execute(['doctor_id' => $doctor_id]);
$gender_data = $gender_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta tags for responsive design and character encoding -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Page title -->
<title>Doctor Dashboard - Patient Health Record System</title>
<!-- Bootstrap 4.5 CSS for responsive layout and components -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- Custom CSS for the design -->
<style>
/* Custom CSS for modern design */
body {
background-color: #f8f9fa;
font-family: Arial, sans-serif;
}
.dashboard-header {
background-color: #4F3F02; /* Brown color */
color: #fff;
padding: 20px;
text-align: center;
border-radius: 8px;
margin-bottom: 30px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}
h1, h2 {
font-weight: bold;
}
.btn-primary {
background-color: #D1C287; /* Light golden color */
border-color: #D1C287;
color: #4F3F02; /* Brown color */
font-weight: bold;
}
.btn-primary:hover {
background-color: #4F3F02; /* Brown color */
border-color: #D1C287;
color: #fff;
}
.btn-secondary {
background-color: #4F3F02; /* Brown color */
border-color: #4F3F02;
color: #fff;
font-weight: bold;
}
.btn-secondary:hover {
background-color: #D1C287; /* Light golden color */
color: #4F3F02; /* Brown color */
}
.filters {
background-color: #fff;
padding: 20px;
border-radius: 8px;
margin-bottom: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.filters .form-control, .filters select {
margin-bottom: 15px;
border: 1px solid #D1C287;
border-radius: 5px;
}
.filters .form-control:focus, .filters select:focus {
border-color: #4F3F02;
box-shadow: none;
}
.table-responsive {
margin-top: 20px;
}
.table {
background-color: #fff;
border-radius: 8px;
overflow: hidden;
}
.table thead th {
background-color: #4F3F02;
color: #fff;
border-color: #4F3F02;
padding: 12px;
text-align: left;
}
th, td {
vertical-align: middle !important;
}
.card {
border: none;
border-radius: 10px;
margin-bottom: 20px;
}
.card .card-title {
color: #4F3F02;
}
/* Responsive adjustments */
@media (max-width: 768px) {
.filters .form-control, .filters select {
margin-bottom: 10px;
}
}
/* Adjust filter button alignment */
.filters .btn-primary {
margin-top: 32px;
}
</style>
</head>
<body>
<div class="container-fluid">
<!-- Dashboard Header -->
<div class="dashboard-header">
<img src="images/white-logo.png" alt="White Logo" style="max-width: 30%; height: auto; margin-bottom: 20px;"> <!-- Logo -->
<h1>Doctor Dashboard</h1>
<p>Welcome, Dr. <?= htmlspecialchars($doctor['name']); ?>!</p>
</div>
<!-- Navigation Buttons -->
<div class="d-flex flex-wrap mb-3">
<a href="view_patient.php" class="btn btn-primary mb-2 mr-2">View Patients</a>
<a href="logout.php" class="btn btn-secondary mb-2">Log Out</a>
</div>
<!-- Filters Section -->
<div class="filters">
<form action="dashboard.php" method="get" class="form-row">
<div class="form-group col-md-3">
<input type="text" name="search" class="form-control" placeholder="Search Patients..." value="<?= htmlspecialchars($search); ?>">
</div>
<div class="form-group col-md-2">
<select name="gender" class="form-control">
<option value="">All Genders</option>
<option value="Male" <?= ($gender_filter == 'Male') ? 'selected' : ''; ?>>Male</option>
<option value="Female" <?= ($gender_filter == 'Female') ? 'selected' : ''; ?>>Female</option>
<option value="Other" <?= ($gender_filter == 'Other') ? 'selected' : ''; ?>>Other</option>
</select>
</div>
<div class="form-group col-md-2">
<select name="status" class="form-control">
<option value="">All Statuses</option>
<?php foreach ($status_options as $option): ?>
<option value="<?= htmlspecialchars($option); ?>" <?= ($status_filter == $option) ? 'selected' : ''; ?>><?= htmlspecialchars($option); ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-2">
<select name="sort_by" class="form-control">
<option value="p.name" <?= ($sort_by == 'p.name') ? 'selected' : ''; ?>>Name</option>
<option value="p.age" <?= ($sort_by == 'p.age') ? 'selected' : ''; ?>>Age</option>
<option value="p.gender" <?= ($sort_by == 'p.gender') ? 'selected' : ''; ?>>Gender</option>
<option value="p.status" <?= ($sort_by == 'p.status') ? 'selected' : ''; ?>>Status</option>
<option value="p.registration_datetime" <?= ($sort_by == 'p.registration_datetime') ? 'selected' : ''; ?>>Registration Time</option>
</select>
</div>
<div class="form-group col-md-2">
<select name="sort_order" class="form-control">
<option value="ASC" <?= ($sort_order == 'ASC') ? 'selected' : ''; ?>>Ascending</option>
<option value="DESC" <?= ($sort_order == 'DESC') ? 'selected' : ''; ?>>Descending</option>
</select>
</div>
<div class="form-group col-md-1">
<button type="submit" class="btn btn-primary btn-block">Apply</button>
</div>
</form>
</div>
<!-- Charts Section -->
<div class="row">
<!-- Patient Status Distribution Chart -->
<div class="col-md-6">
<div class="card">
<div class="card-body">
<h2 class="card-title text-center">Patient Status Distribution</h2>
<canvas id="statusChart" style="height: 300px;"></canvas>
</div>
</div>
</div>
<!-- Gender Distribution Histogram -->
<div class="col-md-6">
<div class="card">
<div class="card-body">
<h2 class="card-title text-center">Gender Distribution</h2>
<canvas id="genderChart" style="height: 300px;"></canvas>
</div>
</div>
</div>
</div>
<!-- Patients Table -->
<div class="table-responsive">
<h2>Your Patients:</h2>
<?php if ($patients): ?>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Patient ID</th>
<th>Name</th>
<th>Username</th>
<th>Age</th>
<th>Gender</th>
<th>Phone</th>
<th>Email</th>
<th>Registration Time</th>
<th>Has Invoice</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($patients as $patient): ?>
<tr>
<td><?= htmlspecialchars($patient['id']); ?></td>
<td><?= htmlspecialchars($patient['name']); ?></td>
<td><?= htmlspecialchars($patient['username']); ?></td>
<td><?= htmlspecialchars($patient['age']); ?></td>
<td><?= htmlspecialchars($patient['gender']); ?></td>
<td><?= htmlspecialchars($patient['phone']); ?></td>
<td><?= htmlspecialchars($patient['email']); ?></td>
<td><?= htmlspecialchars($patient['registration_datetime']); ?></td>
<td>
<?php
// Check if the patient has any invoices
$invoice_stmt = $pdo->prepare("SELECT COUNT(*) FROM invoices WHERE patient_id = ?");
$invoice_stmt->execute([$patient['id']]);
$invoice_count = $invoice_stmt->fetchColumn();
echo $invoice_count > 0 ? '<span class="badge badge-success">Yes</span>' : '<span class="badge badge-danger">No</span>';
?>
</td>
<td><?= htmlspecialchars($patient['status']); ?></td>
<td>
<div class="btn-group" role="group">
<a href="view_patient.php?id=<?= $patient['id']; ?>" class="btn btn-primary btn-sm">View</a>
<a href="edit_patient.php?id=<?= $patient['id']; ?>" class="btn btn-primary btn-sm">Edit</a>
<a href="add_health_record.php?id=<?= $patient['id']; ?>" class="btn btn-primary btn-sm">Add Record</a>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<!-- Pagination -->
<?php if ($total_pages > 1): ?>
<nav aria-label="Page navigation">
<ul class="pagination justify-content-center">
<!-- Previous Button -->
<li class="page-item <?= ($page <= 1) ? 'disabled' : ''; ?>">
<a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<?php
// Display a range of pages around the current page
$range = 2; // Number of pages to show before and after current page
$start = max(1, $page - $range);
$end = min($total_pages, $page + $range);
if ($start > 1) {
echo '<li class="page-item"><a class="page-link" href="?'.http_build_query(array_merge($_GET, ['page' => 1])).'">1</a></li>';
if ($start > 2) {
echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
}
}
for ($i = $start; $i <= $end; $i++) {
echo '<li class="page-item ' . ($i == $page ? 'active' : '') . '">';
echo '<a class="page-link" href="?' . http_build_query(array_merge($_GET, ['page' => $i])) . '">' . $i . '</a>';
echo '</li>';
}
if ($end < $total_pages) {
if ($end < $total_pages - 1) {
echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
}
echo '<li class="page-item"><a class="page-link" href="?' . http_build_query(array_merge($_GET, ['page' => $total_pages])) . '">' . $total_pages . '</a></li>';
}
?>
<!-- Next Button -->
<li class="page-item <?= ($page >= $total_pages) ? 'disabled' : ''; ?>">
<a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
<?php endif; ?>
<?php else: ?>
<p>You have no patients assigned.</p>
<?php endif; ?>
</div>
<!-- Include jQuery and Bootstrap JS for components -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<!-- Popper.js for Bootstrap tooltips (optional) -->
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<!-- Bootstrap 4.5 JS -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<!-- Chart.js Scripts -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- Chart.js Scripts -->
<script>
// Patient Status Distribution Chart
const statusCtx = document.getElementById('statusChart').getContext('2d');
const statusChart = new Chart(statusCtx, {
type: 'pie',
data: {
labels: <?= json_encode(array_column($status_data, 'status')) ?>,
datasets: [{
data: <?= json_encode(array_column($status_data, 'count')) ?>,
backgroundColor: [
'#007bff', // Blue
'#28a745', // Green
'#ffc107', // Yellow
'#6c757d', // Grey
'#17a2b8', // Teal
'#fd7e14', // Orange
'#6610f2' // Purple
],
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'bottom',
},
title: {
display: false
}
}
},
});
// Gender Distribution Histogram Chart
const genderCtx = document.getElementById('genderChart').getContext('2d');
const genderChart = new Chart(genderCtx, {
type: 'bar',
data: {
labels: <?php echo json_encode(array_column($gender_data, 'gender')); ?>,
datasets: [{
label: 'Number of Patients',
data: <?php echo json_encode(array_column($gender_data, 'count')); ?>,
backgroundColor: '#D1C287', // Light golden color
borderColor: '#4F3F02', // Brown color
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
precision: 0,
title: {
display: true,
text: 'Number of Patients'
}
},
x: {
title: {
display: true,
text: 'Gender'
}
}
},
plugins: {
legend: {
display: false,
},
title: {
display: false
}
}
},
});
</script>
</body>
</html>
Key Changes and Improvements:
Fixed SQL Query: Rewrote the SQL subquery for health_records to avoid using window functions (ROW_NUMBER()), ensuring compatibility with MySQL versions before 8.0.
Responsive Design: Used Bootstrap's grid system to display the charts in one row with two columns. This ensures that on smaller screens, the charts stack appropriately while maintaining responsiveness.
Adjusted CSS Styles: Enhanced the CSS for a cleaner and more modern look. Adjusted padding, margins, and colors to improve readability and aesthetics.
Removed Unnecessary Scripts: Removed DataTables CSS and JS, as they were not providing additional features and were being disabled. This simplifies the codebase and reduces load times.
Improved Pagination Links: Updated the pagination to use http_build_query() for proper URL encoding and to retain all GET parameters when navigating between pages.
Aligned with Database Structure: Ensured that all SQL queries and table references match the provided database structure, including the doctors table assumed to exist.
Charts Enhancement: The charts are now fully responsive and display correctly. Adjusted chart options for better visuals and ensured they fit well within the new layout.
Security Measures: Applied htmlspecialchars() to output to prevent XSS attacks and ensure data is displayed safely.
Feel free to further customize the CSS and HTML to match your preferred style. This updated code should work seamlessly with your database and provide a responsive, user-friendly dashboard.