please fix this codes (<?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 have consultation scheduled
// 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.address AS patient_address, /* Added address */
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
";
<!-- Welcome Card -->
<div class="section">
<div class="card">
<div class="card-body">
<h3>Welcome to the Longeva Health Journey Dashboard</h3>
<p>Manage patient surveys, view detailed information, and perform administrative tasks related to the health journey program all in one place.</p>
</div>
</div>
</div>
<!-- Patient Data Table -->
<div class="section">
<h3>Patient Data</h3>
<div class="table-responsive">
<table class="table table-striped table-bordered" id="patientTable">
<thead>
<tr>
<th></th> <!-- For toggle button -->
<th>Patient ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Gender</th>
<th>Age</th>
<th>Address</th> <!-- New Address Column -->
<th>Consultation Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php if ($patients): ?>
<?php foreach ($patients as $patient): ?>
<tr>
<td class="details-control" data-patient-id="<?= htmlspecialchars($patient['patient_id']) ?>"></td>
<td><?= htmlspecialchars($patient['patient_id']) ?></td>
<td><?= htmlspecialchars($patient['patient_name']) ?></td>
<td><?= htmlspecialchars($patient['patient_email']) ?></td>
<td><?= htmlspecialchars($patient['patient_phone']) ?></td>
<td><?= htmlspecialchars($patient['patient_gender']) ?></td>
<td><?= htmlspecialchars($patient['patient_age']) ?></td>
<td><?= htmlspecialchars($patient['patient_address']) ?></td> <!-- Address Data -->
<td><?= htmlspecialchars(date('Y-m-d H:i', strtotime($patient['scheduled_at']))) ?></td>
<td class="action-buttons">
<a href="view_patient.php?id=<?= htmlspecialchars($patient['patient_id']) ?>" class="btn btn-info btn-sm">View</a>
<a href="add_appointment.php?patient_id=<?= htmlspecialchars($patient['patient_id']) ?>" class="btn btn-warning btn-sm">Add Appointment</a>
<a href="delete_patient.php?id=<?= htmlspecialchars($patient['patient_id']) ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this patient?')">Delete</a>
</td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="10" class="text-center">No survey answers found.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
Certainly! I've reviewed your PHP and JavaScript code and identified key issues that need addressing to ensure the table is flexible, error-free, and maintains consistent styling. The primary issue lies in the JavaScript section where PHP variables were incorrectly used within the event handler. Here's the complete, corrected code with detailed explanations:
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 have consultation scheduled
// 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.address AS patient_address,
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
";
$stmt = $pdo->query($sql);
$patients = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "<div class='alert alert-danger'>Database Error: " . htmlspecialchars($e->getMessage()) . "</div>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Longeva Health Journey - Patient Dashboard</title>
<!-- Custom Styles -->
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap');
:root {
--primary-color: #4F3F02;
--secondary-color: #D1C287;
--background-color: #f9f9f9;
--text-color: #333;
--button-hover-color: #c9b458;
--border-radius: 8px;
--transition-speed: 0.3s;
--box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1),
0 1px 3px rgba(0, 0, 0, 0.08);
}
body {
font-family: 'Roboto', sans-serif;
line-height: 1.6;
background-color: var(--background-color);
color: var(--text-color);
margin: 0;
padding: 0;
}
.container-survey {
max-width: 1200px;
margin: 40px auto;
padding: 20px;
background-color: white;
border-radius: var(--border-radius);
box-shadow: var(--box-shadow);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
color: white;
padding: 20px;
text-align: center;
border-radius: calc(var(--border-radius) - 5px) calc(var(--border-radius) - 5px) 0 0;
position: relative;
overflow: hidden;
}
.header h2 {
margin: 0;
font-size: 32px;
font-weight: 700;
}
.section {
margin-top: 20px;
padding: 20px;
background-color: var(--background-color);
border-radius: var(--border-radius);
box-shadow: var(--box-shadow);
transition: transform var(--transition-speed) ease, box-shadow var(--transition-speed) ease;
}
.section:hover {
transform: translateY(-5px);
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2),
0 4px 6px rgba(0, 0, 0, 0.15);
}
.section h3 {
font-size: 24px;
margin-top: 0;
color: var(--primary-color);
border-bottom: 2px solid var(--secondary-color);
padding-bottom: 10px;
}
.action-buttons a {
margin-right: 5px;
}
/* Details Control Styling */
td.details-control {
background: url('https://www.datatables.net/examples/resources/details_open.png') no-repeat center center;
cursor: pointer;
width: 20px;
}
tr.shown td.details-control {
background: url('https://www.datatables.net/examples/resources/details_close.png') no-repeat center center;
}
/* Responsive Enhancements */
@media (max-width: 768px) {
.container-survey {
margin: 20px;
padding: 15px;
}
.header h2 {
font-size: 28px;
}
.section h3 {
font-size: 22px;
}
.btn {
font-size: 12px;
padding: 5px 8px;
}
}
@media (max-width: 480px) {
.header h2 {
font-size: 24px;
}
.section h3 {
font-size: 20px;
}
.btn {
font-size: 10px;
padding: 4px 6px;
}
}
</style>
<!-- DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.4.1/css/responsive.bootstrap5.min.css">
</head>
<body>
<div class="container-survey">
<div class="header">
<h2>Survey Information - Longeva Health Journey</h2>
</div>
<!-- Welcome Card -->
<div class="section">
<div class="card">
<div class="card-body">
<h3>Welcome to the Longeva Health Journey Dashboard</h3>
<p>Manage patient surveys, view detailed information, and perform administrative tasks related to the health journey program all in one place.</p>
</div>
</div>
</div>
<!-- Patient Data Table -->
<div class="section">
<h3>Patient Data</h3>
<div class="table-responsive">
<table class="table table-striped table-bordered" id="patientTable">
<thead>
<tr>
<th></th> <!-- For toggle button -->
<th>Patient ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Gender</th>
<th>Age</th>
<th>Address</th> <!-- New Address Column -->
<th>Consultation Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php if ($patients): ?>
<?php foreach ($patients as $patient): ?>
<tr data-patient='<?= htmlspecialchars(json_encode($patient), ENT_QUOTES, 'UTF-8') ?>'>
<td class="details-control"></td>
<td><?= htmlspecialchars($patient['patient_id']) ?></td>
<td><?= htmlspecialchars($patient['patient_name']) ?></td>
<td><?= htmlspecialchars($patient['patient_email']) ?></td>
<td><?= htmlspecialchars($patient['patient_phone']) ?></td>
<td><?= htmlspecialchars($patient['patient_gender']) ?></td>
<td><?= htmlspecialchars($patient['patient_age']) ?></td>
<td><?= htmlspecialchars($patient['patient_address']) ?></td> <!-- Address Data -->
<td><?= htmlspecialchars(date('Y-m-d H:i', strtotime($patient['scheduled_at']))) ?></td>
<td class="action-buttons">
<a href="view_patient.php?id=<?= htmlspecialchars($patient['patient_id']) ?>" class="btn btn-info btn-sm">View</a>
<a href="add_appointment.php?patient_id=<?= htmlspecialchars($patient['patient_id']) ?>" class="btn btn-warning btn-sm">Add Appointment</a>
<a href="delete_patient.php?id=<?= htmlspecialchars($patient['patient_id']) ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this patient?')">Delete</a>
</td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="10" class="text-center">No survey answers found.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
<!-- Include necessary scripts for DataTables and Bootstrap (if not already included in header.php) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Include Bootstrap JS if necessary -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- Include DataTables JS -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<!-- Include DataTables Responsive JS -->
<script src="https://cdn.datatables.net/responsive/2.4.1/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.4.1/js/responsive.bootstrap5.min.js"></script>
<!-- Initialize DataTables and Implement Child Rows -->
<script>
$(document).ready(function() {
// Initialize DataTables
var table = $('#patientTable').DataTable({
"paging": true,
"searching": true,
"ordering": true,
"info": true,
"lengthChange": true,
"columnDefs": [
{ "orderable": false, "targets": [0, 9] } // Disable ordering on the first and last columns
],
"language": {
"search": "Filter records:",
"lengthMenu": "Show _MENU_ entries",
"info": "Showing _START_ to _END_ of _TOTAL_ patients",
"paginate": {
"previous": "Prev",
"next": "Next"
}
},
"responsive": true
});
// Function to format additional patient details
function format(d) {
return `
<div class="card card-body">
<h5>Additional Information</h5>
<div class="row">
<div class="col-md-4">
<p><strong>Weight:</strong> ${d.patient_weight ? d.patient_weight + ' kg' : 'N/A'}</p>
<p><strong>Height:</strong> ${d.patient_height ? d.patient_height + ' cm' : 'N/A'}</p>
<p><strong>Consent:</strong> ${d.consent ? d.consent : 'N/A'}</p>
</div>
<div class="col-md-4">
<p><strong>Primary Health Goals:</strong> ${d.primary_health_goals ? d.primary_health_goals : 'N/A'}</p>
<p><strong>Health Concerns:</strong> ${d.health_concerns ? d.health_concerns : 'N/A'}</p>
<p><strong>Exercise Frequency:</strong> ${d.exercise_frequency ? d.exercise_frequency : 'N/A'}</p>
</div>
<div class="col-md-4">
<p><strong>Diet:</strong> ${d.diet ? d.diet + (d.diet_specify ? ' (' + d.diet_specify + ')' : '') : 'N/A'}</p>
<p><strong>Sleep Average:</strong> ${d.sleep_average ? d.sleep_average : 'N/A'}</p>
<p><strong>Smoking Status:</strong> ${d.smoking_status ? d.smoking_status : 'N/A'}</p>
<p><strong>Chronic Conditions:</strong> ${d.chronic_conditions ? d.chronic_conditions + (d.chronic_conditions_specify ? ' (' + d.chronic_conditions_specify + ')' : '') : 'N/A'}</p>
<p><strong>Medications:</strong> ${d.medications ? d.medications + (d.medications_list ? ' (' + d.medications_list + ')' : '') : 'N/A'}</p>
<p><strong>Major Surgeries:</strong> ${d.major_surgeries ? d.major_surgeries + (d.major_surgeries_specify ? ' (' + d.major_surgeries_specify + ')' : '') : 'N/A'}</p>
</div>
</div>
</div>
`;
}
// Add event listener for opening and closing details
$('#patientTable tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
var rowData = tr.attr('data-patient');
var patientData = rowData ? JSON.parse(rowData) : {};
row.child(format(patientData)).show();
tr.addClass('shown');
}
});
});
</script>
</body>
<?php
// Include the footer
include '../includes/footer.php';
?>
Detailed Explanation of Changes and Enhancements
Proper Data Handling Between PHP and JavaScript:
Issue: Originally, PHP variables were being used directly inside the JavaScript event handler, which caused scoping issues and potential errors.
Solution: Each <tr> now includes a data-patient attribute containing a JSON-encoded string of the patient's data. This allows JavaScript to safely parse and use the data when needed.
Secure JSON Encoding:
Used json_encode($patient) with htmlspecialchars to ensure that the JSON string is safely embedded within the HTML attribute, preventing potential injection attacks.
Added ENT_QUOTES to htmlspecialchars to ensure both double and single quotes are properly escaped.
JavaScript Enhancements:
Parsing data-patient: In the event handler, the data-patient attribute is retrieved and parsed using JSON.parse to convert it back into a JavaScript object.
Error Handling: If, for any reason, the data-patient attribute is missing or malformed, the code gracefully handles it by showing "N/A" or a default message.
Dynamic Content Display: The format function now checks if each piece of data exists before displaying it. If a piece of data is missing, it displays "N/A" to ensure the UI remains clean and informative.
Styling Consistencies and Enhancements:
Details Control Styling: Added a fixed width to the .details-control class to ensure the toggle icons are properly aligned.
Responsive Design: Ensured that the table and its contents remain responsive across different screen sizes by utilizing Bootstrap's grid system and DataTables' responsive features.
User Experience: Added hover effects to sections to enhance interactivity and visual appeal.
DataTables Integration:
Responsive Integration: Included the necessary CSS and JS for DataTables' responsive extension to ensure the table adjusts gracefully on smaller screens.
Initialization Consistency: Ensured that DataTables is initialized with all necessary options, maintaining the desired functionalities like paging, searching, and ordering.
Final Notes
By implementing these changes, the patient data table becomes more robust, secure, and user-friendly. The separation of data handling between PHP and JavaScript ensures that the application remains scalable and maintainable. Additionally, maintaining consistent styling and responsiveness guarantees a seamless experience across different devices and screen sizes.
Feel free to integrate this updated code into your project. If you encounter any further issues or need additional enhancements, don't hesitate to reach out!
DOCTYPE Declaration: Added <!DOCTYPE html> to ensure the document is rendered in standards mode.
Meta Tags: Included essential meta tags like charset and viewport for proper rendering and responsiveness on various devices.
Title Tag: Added a descriptive <title> to improve SEO and provide a clear context in browser tabs.
Code Organization and Readability:
Indentation and Formatting: Ensured consistent indentation and formatting for better readability and maintainability.
Comments: Added comments to explain key sections of the code, aiding future developers or maintainers in understanding the flow and purpose of each part.
Security Considerations:
Output Escaping: Used htmlspecialchars to escape all dynamic content, preventing Cross-Site Scripting (XSS) attacks.
Confirmation on Delete: Retained the confirmation prompt when deleting a patient to prevent accidental deletions.