in accountant/manage_payments.php (<?php
session_start();
require_once '../db_connect.php';
// Check if the accountant is logged in
if (!isset($_SESSION['accountant_id'])) {
header("Location: login.php");
exit();
}
try {
// Fetch payments along with patient name and invoice number
stmt=pdo->prepare("
SELECT payments.*, patients.name AS patient_name, invoices.id AS invoice_number
FROM payments
JOIN patients ON payments.patient_id = patients.id
JOIN invoices ON payments.invoice_id = invoices.id
ORDER BY payment_date DESC
");
stmt−>execute();payments = stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException e) {
echo "Error fetching payments: " . $e->getMessage();
exit();
}
?>
Certainly! Below is a complete implementation of a delete_payment.php script that securely handles the deletion of a payment record. Additionally, I'll provide guidance on how to update your existing manage_payments.php to utilize this new deletion script effectively.
1. delete_payment.php
This script processes the deletion of a payment. It ensures that the user is authenticated, validates the payment_id, performs the deletion, and redirects back to manage_payments.php with appropriate success or error messages.
Full Code: delete_payment.php
php
<?php
session_start();
require_once '../db_connect.php';
// Check if the accountant is logged in
if (!isset($_SESSION['accountant_id'])) {
header("Location: login.php");
exit();
}
// Check if the form is submitted via POST and contains 'payment_id'
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['payment_id'])) {
// Retrieve and sanitize the payment ID
$payment_id = $_POST['payment_id'];
// Validate that payment_id is a positive integer
if (!filter_var($payment_id, FILTER_VALIDATE_INT, ["options" => ["min_range" => 1]])) {
$_SESSION['error'] = "Invalid payment ID.";
header("Location: manage_payments.php");
exit();
}
try {
// Optional: Verify that the payment exists before attempting deletion
$stmt = $pdo->prepare("SELECT * FROM payments WHERE id = ?");
$stmt->execute([$payment_id]);
$payment = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$payment) {
$_SESSION['error'] = "Payment not found.";
header("Location: manage_payments.php");
exit();
}
// Perform the deletion
$deleteStmt = $pdo->prepare("DELETE FROM payments WHERE id = ?");
$deleteStmt->execute([$payment_id]);
// Check if the deletion was successful
if ($deleteStmt->rowCount()) {
$_SESSION['success'] = "Payment deleted successfully.";
} else {
$_SESSION['error'] = "Failed to delete the payment. Please try again.";
}
} catch (PDOException $e) {
// Handle potential database errors
$_SESSION['error'] = "Error deleting payment: " . $e->getMessage();
}
// Redirect back to the Manage Payments page
header("Location: manage_payments.php");
exit();
} else {
// If accessed without POST data, redirect back with an error
$_SESSION['error'] = "Invalid request.";
header("Location: manage_payments.php");
exit();
}
?>
Explanation of the Code:
Session Management and Authentication:
Starts the session to access session variables.
Checks if the accountant_id is set in the session to confirm that the user is logged in. If not, redirects to login.php.
Handling POST Request:
Ensures that the request method is POST and that it contains a payment_id.
Sanitizes and validates the payment_id to ensure it's a positive integer.
Database Operations:
Verification: Optionally checks if the payment with the given payment_id exists to prevent deletion of non-existent records.
Deletion: Executes a prepared statement to delete the payment securely, preventing SQL injection.
Feedback: Sets session variables success or error based on the outcome of the deletion.
Redirection:
After attempting deletion, redirects the user back to manage_payments.php where success or error messages can be displayed.
2. Update manage_payments.php to Use delete_payment.php
To utilize the new delete_payment.php script, you need to update the form action in your manage_payments.php. Additionally, it's beneficial to display success and error messages to inform the user about the outcome of their actions.
Steps to Update manage_payments.php:
Change the Form Action:
Update the form's action attribute to point to delete_payment.php instead of submitting to itself.
php
<form action="delete_payment.php" method="POST" style="display:inline-block;">
<input type="hidden" name="payment_id" value="<?php echo $payment['id']; ?>">
<button type="submit" name="delete_payment" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this payment?');">Delete</button>
</form>
Display Success and Error Messages:
Add the following block of code below the dashboard header or at an appropriate location to display feedback messages.
Add the above code right after the dashboard header and before the main container:
html
3. (Optional) Implement CSRF Protection
For enhanced security, especially to protect against Cross-Site Request Forgery (CSRF) attacks, it's advisable to implement CSRF tokens in your forms. Below is a brief overview of how you can add CSRF protection.
Steps to Implement CSRF Protection:
Generate a CSRF Token:
Add the following code at the beginning of manage_payments.php (after session_start();) to generate and store a CSRF token if not already set.
php
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
Include the CSRF Token in the Form:
Add a hidden input field within your deletion form to include the CSRF token.
php
<form action="delete_payment.php" method="POST" style="display:inline-block;">
<input type="hidden" name="payment_id" value="<?php echo $payment['id']; ?>">
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
<button type="submit" name="delete_payment" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this payment?');">Delete</button>
</form>
Validate the CSRF Token in delete_payment.php:
Before processing the deletion, verify that the received CSRF token matches the one stored in the session.
Implementing CSRF protection enhances the security of your application by ensuring that deletion requests are legitimate and originated from authenticated users.
4. Final Notes
Error Handling: Ensure that your db_connect.php is properly configured to handle database connections and any potential errors.
User Feedback: The provided implementation uses Bootstrap alerts to inform users about the success or failure of their actions. Ensure that Bootstrap's JavaScript is properly loaded to enable functionalities like dismissing alerts.
Permissions: If your application has different user roles, you might want to add additional checks to ensure that only authorized users can delete payments.
By following the above steps, you can safely and effectively implement a payment deletion feature in your accounting system. If you have any further questions or need more assistance, feel free to ask!
Make sure that delete_payment.php is correctly placed relative to manage_payments.php. In the provided delete_payment.php, it includes ../db_connect.php, indicating that it resides one directory deeper than db_connect.php. Adjust the paths accordingly based on your project structure.