Certainly! Below is the complete page8.php file with the Address input integrated into both the backend PHP logic and the frontend HTML form. This implementation ensures that the address is properly fetched from and stored into the database, and it's displayed within the form for the user to update if necessary.
Key Additions:
-
Backend PHP:
- Initialization: Added the
$address variable.
- Fetching Data: Modified the SQL
SELECT statement to include the address field.
- Sanitization and Validation: Collected, sanitized, and validated the
address input from the user.
- Database Operations: Updated the SQL
UPDATE and INSERT statements to handle the address field.
-
Frontend HTML:
- Form Field: Added a
textarea for the address input within the form to allow multi-line input.
<?php
// longeva_health_journey/pages/page8.php
// Enable error reporting for debugging (Remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Start session and include database connection
session_start();
require '../db_connect.php';
// Check if patient_id is set; if not, redirect to page3.php to collect information
if (!isset($_SESSION['patient_id'])) {
header("Location: page3.php");
exit();
}
$errors = [];
// Initialize variables
$name = '';
$email = '';
$phone = '';
$gender = '';
$age = '';
$weight = '';
$height = '';
$address = '';
$scheduled_at = '';
// Function to safely escape output
function safe_htmlspecialchars($string) {
return htmlspecialchars($string ?? '', ENT_QUOTES, 'UTF-8');
}
// Fetch existing patient_basic_info and consultation date/time to pre-fill the form
try {
// Fetch patient basic info including address
$stmt = $pdo->prepare("SELECT name, email, phone, gender, age, weight, height, address FROM patient_basic_info WHERE patient_id = ?");
$stmt->execute([$_SESSION['patient_id']]);
$basic_info = $stmt->fetch(PDO::FETCH_ASSOC);
if ($basic_info) {
$name = safe_htmlspecialchars($basic_info['name']);
$email = safe_htmlspecialchars($basic_info['email']);
$phone = safe_htmlspecialchars($basic_info['phone']);
$gender = safe_htmlspecialchars($basic_info['gender']);
$age = safe_htmlspecialchars($basic_info['age']);
$weight = safe_htmlspecialchars($basic_info['weight']);
$height = safe_htmlspecialchars($basic_info['height']);
$address = safe_htmlspecialchars($basic_info['address']);
}
// Fetch existing consultation date and time if available
$stmt = $pdo->prepare("SELECT scheduled_at FROM patient_consultation WHERE patient_id = ?");
$stmt->execute([$_SESSION['patient_id']]);
$consultation = $stmt->fetch();
if ($consultation) {
// Ensure the datetime format is compatible with input[type="datetime-local"]
$scheduled_at = date('Y-m-d\TH:i', strtotime($consultation['scheduled_at']));
}
} catch (PDOException $e) {
$errors[] = "Database Error: " . safe_htmlspecialchars($e->getMessage());
}
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Collect and sanitize inputs
$name = isset($_POST['name']) ? safe_htmlspecialchars(trim($_POST['name'])) : '';
$email = isset($_POST['email']) ? filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL) : '';
$phone = isset($_POST['phone']) ? safe_htmlspecialchars(trim($_POST['phone'])) : '';
$gender = isset($_POST['gender']) ? safe_htmlspecialchars(trim($_POST['gender'])) : '';
$age = isset($_POST['age']) ? intval($_POST['age']) : '';
$weight = isset($_POST['weight']) ? floatval($_POST['weight']) : '';
$height = isset($_POST['height']) ? floatval($_POST['height']) : '';
$address = isset($_POST['address']) ? safe_htmlspecialchars(trim($_POST['address'])) : '';
$scheduled_at = isset($_POST['scheduled_at']) ? safe_htmlspecialchars(trim($_POST['scheduled_at'])) : '';
// Validate inputs
if (empty($name)) {
$errors[] = "Name is required.";
}
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "A valid Email is required.";
}
if (empty($phone)) {
$errors[] = "Phone number is required.";
} elseif (!preg_match('/^[0-9+\-\s()]{7,20}$/', $phone)) {
$errors[] = "Please enter a valid phone number.";
}
if (empty($gender)) {
$errors[] = "Gender is required.";
}
if (empty($age) || $age <= 0) {
$errors[] = "Valid age is required.";
}
if (empty($weight) || $weight <= 0) {
$errors[] = "Valid weight is required.";
}
if (empty($height) || $height <= 0) {
$errors[] = "Valid height is required.";
}
if (empty($address)) {
$errors[] = "Address is required.";
}
if (empty($scheduled_at)) {
$errors[] = "Please select a consultation date and time.";
} else {
// Validate datetime format
$date = DateTime::createFromFormat('Y-m-d\TH:i', $scheduled_at);
if (!$date) {
$errors[] = "Invalid date and time format.";
}
}
if (empty($errors)) {
try {
// Begin transaction to ensure both inserts/updates are successful
$pdo->beginTransaction();
// Update or Insert into patient_basic_info
// Check if patient_basic_info already exists
$stmt = $pdo->prepare("SELECT patient_id FROM patient_basic_info WHERE patient_id = ?");
$stmt->execute([$_SESSION['patient_id']]);
if ($stmt->rowCount() > 0) {
// Update existing record
$stmt = $pdo->prepare("UPDATE patient_basic_info SET name = ?, email = ?, phone = ?, gender = ?, age = ?, weight = ?, height = ?, address = ? WHERE patient_id = ?");
$stmt->execute([$name, $email, $phone, $gender, $age, $weight, $height, $address, $_SESSION['patient_id']]);
} else {
// Insert new record with patient_id
$stmt = $pdo->prepare("INSERT INTO patient_basic_info (patient_id, name, email, phone, gender, age, weight, height, address) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([$_SESSION['patient_id'], $name, $email, $phone, $gender, $age, $weight, $height, $address]);
}
// Update or Insert into patient_consultation
$stmt = $pdo->prepare("SELECT patient_id FROM patient_consultation WHERE patient_id = ?");
$stmt->execute([$_SESSION['patient_id']]);
if ($stmt->rowCount() > 0) {
// Update existing consultation
$stmt = $pdo->prepare("UPDATE patient_consultation SET scheduled_at = ? WHERE patient_id = ?");
$stmt->execute([$scheduled_at, $_SESSION['patient_id']]);
} else {
// Insert new consultation
$stmt = $pdo->prepare("INSERT INTO patient_consultation (patient_id, scheduled_at) VALUES (?, ?)");
$stmt->execute([$_SESSION['patient_id'], $scheduled_at]);
}
// Commit transaction
$pdo->commit();
// Redirect to page10.php after successful submission
header("Location: page10.php");
exit();
} catch (PDOException $e) {
// Rollback transaction on error
$pdo->rollBack();
$errors[] = "Database Error: " . safe_htmlspecialchars($e->getMessage());
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Your Information</title>
<link rel="stylesheet" href="../assets/css/styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Optional: Add Bootstrap for better styling -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"/>
</head>
<body>
<div class="container mt-5">
<div class="header text-center mb-4">
<img src="../assets/images/white-logo.png" alt="Longeva Logo" style="width:25%;">
<h2>Your Information</h2>
</div>
<div class="section">
<h3>Ensure Your Details Are Correct</h3>
<p>Providing accurate information helps us serve you better.</p>
<?php
if (!empty($errors)) {
echo '<div class="error alert alert-danger">';
foreach($errors as $error){
echo "<p>" . safe_htmlspecialchars($error) . "</p>";
}
echo '</div>';
}
?>
<form method="POST" action="">
<!-- Name -->
<div class="form-group">
<label for="name">Name:<span class="text-danger">*</span></label>
<input type="text" id="name" name="name" class="form-control" value="<?php echo safe_htmlspecialchars($name); ?>" required>
</div>
<!-- Email -->
<div class="form-group">
<label for="email">Email:<span class="text-danger">*</span></label>
<input type="email" id="email" name="email" class="form-control" value="<?php echo safe_htmlspecialchars($email); ?>" required>
</div>
<!-- Phone Number -->
<div class="form-group">
<label for="phone">Phone Number:<span class="text-danger">*</span></label>
<input type="tel" id="phone" name="phone" class="form-control" value="<?php echo safe_htmlspecialchars($phone); ?>" required>
</div>
<!-- Gender -->
<div class="form-group">
<label for="gender">Gender:<span class="text-danger">*</span></label>
<select id="gender" name="gender" class="form-control" required>
<option value="">--Select Gender--</option>
<option value="Male" <?php if($gender === 'Male') echo 'selected'; ?>>Male</option>
<option value="Female" <?php if($gender === 'Female') echo 'selected'; ?>>Female</option>
<option value="Other" <?php if($gender === 'Other') echo 'selected'; ?>>Other</option>
</select>
</div>
<!-- Age -->
<div class="form-group">
<label for="age">Age:<span class="text-danger">*</span></label>
<input type="number" id="age" name="age" class="form-control" min="0" value="<?php echo safe_htmlspecialchars($age); ?>" required>
</div>
<!-- Weight -->
<div class="form-group">
<label for="weight">Weight (kg):<span class="text-danger">*</span></label>
<input type="number" step="0.1" id="weight" name="weight" class="form-control" min="0" value="<?php echo safe_htmlspecialchars($weight); ?>" required>
</div>
<!-- Height -->
<div class="form-group">
<label for="height">Height (cm):<span class="text-danger">*</span></label>
<input type="number" step="0.1" id="height" name="height" class="form-control" min="0" value="<?php echo safe_htmlspecialchars($height); ?>" required>
</div>
<!-- Address -->
<div class="form-group">
<label for="address">Address:<span class="text-danger">*</span></label>
<textarea id="address" name="address" class="form-control" rows="3" required><?php echo safe_htmlspecialchars($address); ?></textarea>
</div>
<!-- Consultation Date and Time -->
<div class="form-group">
<label for="scheduled_at">Select Consultation Date and Time:<span class="text-danger">*</span></label>
<input type="datetime-local" id="scheduled_at" name="scheduled_at" class="form-control" value="<?php echo safe_htmlspecialchars($scheduled_at); ?>" required>
</div>
<button type="submit" class="btn btn-primary">Save & Continue</button>
</form>
</div>
</div>
<!-- Optional: Include Bootstrap JS for better interactivity -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Explanation of the Additions:
-
Backend (PHP):
-
Initialization:
$address = '';
-
Fetching Data from Database:
Updated the SELECT statement to include the address field:
$stmt = $pdo->prepare("SELECT name, email, phone, gender, age, weight, height, address FROM patient_basic_info WHERE patient_id = ?");
Assigned the fetched address to the $address variable:
$address = safe_htmlspecialchars($basic_info['address']);
-
Handling Form Submission:
-
Collecting and Sanitizing Address:
$address = isset($_POST['address']) ? safe_htmlspecialchars(trim($_POST['address'])) : '';
-
Validating Address:
if (empty($address)) {
$errors[] = "Address is required.";
}
-
Database Update/Insert Including Address:
// Update existing record
$stmt = $pdo->prepare("UPDATE patient_basic_info SET name = ?, email = ?, phone = ?, gender = ?, age = ?, weight = ?, height = ?, address = ? WHERE patient_id = ?");
$stmt->execute([$name, $email, $phone, $gender, $age, $weight, $height, $address, $_SESSION['patient_id']]);
// Insert new record with address
$stmt = $pdo->prepare("INSERT INTO patient_basic_info (patient_id, name, email, phone, gender, age, weight, height, address) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([$_SESSION['patient_id'], $name, $email, $phone, $gender, $age, $weight, $height, $address]);
-
Frontend (HTML):
Important Notes:
-
Database Schema: Ensure that the patient_basic_info table in your database has an address column to store the patient's address. If it doesn't exist, you can add it using the following SQL command:
ALTER TABLE patient_basic_info ADD COLUMN address VARCHAR(255) NOT NULL;
Adjust the VARCHAR(255) to a suitable length based on your requirements.
-
Security: The safe_htmlspecialchars function is used to prevent Cross-Site Scripting (XSS) by escaping special characters. Always sanitize and validate user inputs to protect against SQL Injection and other security vulnerabilities.
-
Styling: This implementation uses Bootstrap for improved styling and responsiveness. Ensure that Bootstrap's CSS and JS files are correctly linked. If you prefer not to use Bootstrap, you can adjust the classes and styles accordingly.
-
Error Handling: All database operations are wrapped in try-catch blocks with transactions to ensure data integrity. Errors are captured and displayed to the user in a user-friendly manner.
-
User Experience: The required attribute in form fields ensures that users cannot submit the form without filling in the necessary information. Additionally, validation messages guide users to correct any input errors.
By integrating the address input as shown above, your form will now collect and store the patient's address along with their other personal information and consultation details.