Certainly! To update your Kaak Alia Management System with the desired changes—such as modifying the database structure, ensuring that product names are displayed when adding orders, supporting multiple product additions per order, implementing percentage-based discounts, and enhancing the overall organization and professionalism of your code—we'll follow a structured approach. This comprehensive guide will cover:
- Backing Up Existing Data
- Updating the Database Structure
- Modifying the PHP Code for Adding Orders
- Ensuring Discounts are Percentage-Based
- Final Touches and Best Practices
1. Backing Up Existing Data
Before making any changes, it’s crucial to back up your existing database to prevent data loss in case of unforeseen issues.
Steps:
-
Access phpMyAdmin:
- Navigate to your phpMyAdmin interface (usually accessible via
http://yourdomain.com/phpmyadmin).
-
Select Your Database:
- Choose the
u406552082_kaakalia database from the list on the left.
-
Export the Database:
- Click on the Export tab.
- Choose the Quick export method and SQL as the format.
- Click Go to download the
.sql file.
-
Store the Backup Securely:
- Save the backup file in a secure location on your local machine or another safe storage solution.
2. Updating the Database Structure
We'll update the database to support multiple products per order, switch discounts to percentage-based, and optimize table structures for clarity and professionalism.
Key Changes:
- Remove
product_id, quantity, etc., from the orders table.
- Ensure all products associated with an order are handled via the
order_items table.
- Change discount fields to store percentage values instead of fixed amounts.
- Enhance table definitions for better clarity and normalization.
Updated SQL Dump:
Below is the updated SQL script incorporating the above changes. This script drops existing tables and recreates them with the new structure.
-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Nov 09, 2024 at 11:52 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_kaakalia`
*/
CREATE DATABASE IF NOT EXISTS `u406552082_kaakalia` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE `u406552082_kaakalia`;
-- --------------------------------------------------------
--
-- Table structure for table `customers`
--
DROP TABLE IF EXISTS `customers`;
CREATE TABLE `customers` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`contact` VARCHAR(50) DEFAULT NULL,
`delivery_address` TEXT DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `orders`
--
DROP TABLE IF EXISTS `orders`;
CREATE TABLE `orders` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`customer_id` INT(11) NOT NULL,
`status` ENUM('Pending','In Progress','Completed','Delivered') DEFAULT 'Pending',
`order_date` DATETIME DEFAULT CURRENT_TIMESTAMP,
`delivery_datetime` DATETIME DEFAULT NULL,
`delivery_date` DATE DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `customer_id` (`customer_id`),
CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `order_items`
--
DROP TABLE IF EXISTS `order_items`;
CREATE TABLE `order_items` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`order_id` INT(11) NOT NULL,
`product_id` INT(11) NOT NULL,
`quantity` INT(11) NOT NULL DEFAULT 1,
`packaging_preferences` VARCHAR(255) DEFAULT NULL,
`discount_percentage` DECIMAL(5,2) DEFAULT 0.00,
`discount_reason` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `order_id` (`order_id`),
KEY `product_id` (`product_id`),
CONSTRAINT `order_items_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE,
CONSTRAINT `order_items_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
DROP TABLE IF EXISTS `products`;
CREATE TABLE `products` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`size` VARCHAR(50) DEFAULT NULL,
`price` DECIMAL(10,2) NOT NULL,
`category` VARCHAR(50) DEFAULT NULL,
`thumbnail` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(50) NOT NULL,
`password` VARCHAR(255) NOT NULL,
`role` ENUM('admin','staff') NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Indexes and constraints are defined above with each table creation
--
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 */;
Explanation of Changes:
-
Orders Table:
- Removed
product_id, quantity, packaging_preferences, discount_amount, and discount_reason from the orders table. This ensures that all product-related details are managed within the order_items table, adhering to normalization principles.
-
Order_Items Table:
- Added
discount_percentage instead of discount_amount to store percentage-based discounts.
- Retained
packaging_preferences, quantity, and discount_reason for flexibility.
-
Product Selection in Orders:
- Utilizing the
order_items table allows each order to have multiple associated products, making the system more scalable and organized.
3. Modifying the PHP Code for Adding Orders
We'll update the add_order.php script to accommodate the new database structure, ensure that product names are displayed when adding orders, support multiple products, and implement percentage-based discounts.
Full Updated add_order.php Code:
<?php
// public/orders/add_order.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Start output buffering to prevent "headers already sent" errors
ob_start();
// Include authentication and database connection **before** any output
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
// Initialize variables
$success = '';
$error = '';
// Fetch products for selection
$products_sql = "SELECT * FROM products ORDER BY name ASC";
$products_result = $conn->query($products_sql);
if (!$products_result) {
die("Error fetching products: " . $conn->error);
}
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Sanitize and validate input
$customer_name = trim($_POST['customer_name']);
$contact = trim($_POST['contact']);
$delivery_address = trim($_POST['delivery_address']);
$delivery_datetime = isset($_POST['delivery_datetime']) && !empty($_POST['delivery_datetime']) ? trim($_POST['delivery_datetime']) : null;
// Handle multiple products
$product_ids = isset($_POST['product_id']) ? $_POST['product_id'] : [];
$quantities = isset($_POST['quantity']) ? $_POST['quantity'] : [];
$packaging_preferences = isset($_POST['packaging_preferences']) ? $_POST['packaging_preferences'] : [];
$apply_discount = isset($_POST['apply_discount']) ? $_POST['apply_discount'] : [];
$discount_percentages = isset($_POST['discount_percentage']) ? $_POST['discount_percentage'] : [];
$discount_reasons = isset($_POST['discount_reason']) ? $_POST['discount_reason'] : [];
// Basic validation
if (empty($customer_name)) {
$error = "Customer name is required.";
} elseif (empty($product_ids) || !is_array($product_ids)) {
$error = "At least one product must be selected.";
} else {
// Validate each product entry
foreach ($product_ids as $index => $pid) {
if (empty($pid)) {
$error = "Product selection is required for all items.";
break;
}
if (intval($quantities[$index]) <= 0) {
$error = "Quantity must be at least 1 for all items.";
break;
}
// If discount is applied, validate discount fields
if (isset($apply_discount[$index])) {
$discount = trim($discount_percentages[$index]);
$reason = trim($discount_reasons[$index]);
if ($discount === '') {
$error = "Discount percentage is required if discount is applied.";
break;
}
if (!is_numeric($discount) || floatval($discount) < 0 || floatval($discount) > 100) {
$error = "Invalid discount percentage for product. It must be between 0 and 100.";
break;
}
if (empty($reason)) {
$error = "Discount reason is required if discount is applied.";
break;
}
}
}
if ($delivery_datetime && !preg_match("/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/", $delivery_datetime)) {
$error = "Invalid delivery date and time format.";
} elseif ($delivery_datetime && strtotime(str_replace('T', ' ', $delivery_datetime)) < strtotime(date('Y-m-d H:i'))) {
$error = "Delivery date and time cannot be in the past.";
}
}
if (empty($error)) {
// Start transaction
$conn->begin_transaction();
try {
// Insert into customers table using prepared statement
$stmt = $conn->prepare("INSERT INTO customers (name, contact, delivery_address) VALUES (?, ?, ?)");
if (!$stmt) {
throw new Exception("Prepare statement failed: " . $conn->error);
}
$stmt->bind_param("sss", $customer_name, $contact, $delivery_address);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
$customer_id = $stmt->insert_id;
$stmt->close();
// Insert into orders table using prepared statement
$stmt = $conn->prepare("INSERT INTO orders (customer_id, status, delivery_datetime, delivery_date) VALUES (?, 'Pending', ?, ?)");
if (!$stmt) {
throw new Exception("Prepare statement failed: " . $conn->error);
}
// Convert delivery_datetime to appropriate formats
$delivery_datetime_db = $delivery_datetime ? date('Y-m-d H:i:s', strtotime($delivery_datetime)) : null;
$delivery_date = $delivery_datetime ? date('Y-m-d', strtotime($delivery_datetime)) : null;
$stmt->bind_param("iss", $customer_id, $delivery_datetime_db, $delivery_date);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
$order_id = $stmt->insert_id;
$stmt->close();
// Insert products into order_items table
if (count($product_ids) > 0) {
$stmt = $conn->prepare("INSERT INTO order_items (order_id, product_id, quantity, packaging_preferences, discount_percentage, discount_reason) VALUES (?, ?, ?, ?, ?, ?)");
if (!$stmt) {
throw new Exception("Prepare statement failed: " . $conn->error);
}
// Loop through each product
for ($i = 0; $i < count($product_ids); $i++) {
$pid = intval($product_ids[$i]);
$qty = intval($quantities[$i]);
$pack_pref = trim($packaging_preferences[$i]);
$discount_pct = isset($apply_discount[$i]) ? floatval(trim($discount_percentages[$i])) : 0.00;
$discount_rs = isset($apply_discount[$i]) ? trim($discount_reasons[$i]) : null;
$stmt->bind_param("iiisss", $order_id, $pid, $qty, $pack_pref, $discount_pct, $discount_rs);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
}
$stmt->close();
}
// Commit transaction
$conn->commit();
// Redirect to view_orders.php after successful addition with success parameter
header("Location: view_orders.php?success=1");
exit();
} catch (Exception $e) {
// Rollback transaction
$conn->rollback();
$error = "Error adding order: " . $e->getMessage();
}
}
}
// Now include the header AFTER form handling
require_once '../../includes/header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add New Order - Kaak Alia Management System</title>
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="/kaak_alia_management_system/assets/bootstrap/css/bootstrap.min.css">
<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
<!-- Embedded Custom Styles -->
<style>
/* Your existing styles remain unchanged */
/* ... (omitted for brevity) ... */
</style>
<!-- Additional JavaScript for dynamic product addition and discount handling -->
<script>
function addProductRow() {
const productContainer = document.getElementById('products-container');
const productCount = productContainer.children.length;
const productRow = document.createElement('div');
productRow.className = 'product-row border p-3 mb-3';
productRow.innerHTML = `
<div class="row">
<div class="col-md-4">
<label class="form-label" for="product_id_${productCount}">Product <span class="text-danger">*</span></label>
<select name="product_id[]" id="product_id_${productCount}" class="form-control" required>
<option value="">Select Product</option>
<?php
// Reset the products_result pointer
$products_result->data_seek(0);
while($product = $products_result->fetch_assoc()): ?>
<option value="<?= htmlspecialchars($product['id']) ?>">
<?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
</option>
<?php endwhile; ?>
</select>
</div>
<div class="col-md-2">
<label class="form-label" for="quantity_${productCount}">Quantity <span class="text-danger">*</span></label>
<input type="number" name="quantity[]" id="quantity_${productCount}" class="form-control" min="1" value="1" required>
</div>
<div class="col-md-3">
<label class="form-label" for="packaging_preferences_${productCount}">Packaging Preferences</label>
<input type="text" name="packaging_preferences[]" id="packaging_preferences_${productCount}" class="form-control" placeholder="e.g., Gift Wrap">
</div>
<div class="col-md-3">
<label class="form-label" for="discount_${productCount}">Apply Discount</label>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="discount_checkbox_${productCount}" name="apply_discount[]">
<label class="form-check-label" for="discount_checkbox_${productCount}">
Yes
</label>
</div>
<div id="discount_fields_${productCount}" style="display: none; margin-top: 10px;">
<label class="form-label" for="discount_percentage_${productCount}">Discount Percentage (%) <span class="text-danger">*</span></label>
<input type="number" name="discount_percentage[]" id="discount_percentage_${productCount}" class="form-control" min="0" max="100" step="0.01" placeholder="Enter discount percentage">
<label class="form-label mt-2" for="discount_reason_${productCount}">Discount Reason <span class="text-danger">*</span></label>
<input type="text" name="discount_reason[]" id="discount_reason_${productCount}" class="form-control" placeholder="Enter reason for discount">
</div>
</div>
<div class="col-md-12 d-flex justify-content-end mt-3">
<button type="button" class="remove-product-button btn btn-danger btn-sm" onclick="removeProductRow(this)">Remove</button>
</div>
</div>
`;
productContainer.appendChild(productRow);
// Add event listener for the new discount checkbox
const newCheckbox = productRow.querySelector(`[id="discount_checkbox_${productCount}"]`);
newCheckbox.addEventListener('change', function() {
toggleDiscountFields(this, productCount);
});
}
function removeProductRow(button) {
const productRow = button.closest('.product-row');
productRow.remove();
}
// Toggle discount fields based on checkbox
function toggleDiscountFields(checkbox, count) {
const discountFields = document.getElementById(`discount_fields_${count}`);
if (checkbox.checked) {
discountFields.style.display = 'block';
} else {
discountFields.style.display = 'none';
// Clear discount inputs
discountFields.querySelectorAll('input').forEach(input => input.value = '');
}
}
// Add event listeners to existing discount checkboxes on page load
function initializeDiscountToggle() {
const discountCheckboxes = document.querySelectorAll('input[name="apply_discount[]"]');
discountCheckboxes.forEach((checkbox, index) => {
checkbox.addEventListener('change', function() {
toggleDiscountFields(this, index);
});
});
}
// Initialize on DOM content loaded
document.addEventListener('DOMContentLoaded', function() {
// Add initial product row if none exist
if (document.getElementById('products-container').children.length === 0) {
addProductRow();
}
// Initialize discount toggles
initializeDiscountToggle();
});
</script>
</head>
<body>
<!-- Header Already Included via header.php -->
<main class='.container-body'>
<!-- Welcome Section -->
<div class="welcome-section mt-20">
<h3>Welcome to the Kaak Alia Management System!</h3>
<hr>
</div>
<!-- Form Container -->
<div class="form-container">
<h3>Add New Order</h3>
<?php if (!empty($error)): ?>
<div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<form method="POST" action="add_order.php">
<!-- Customer Details -->
<div class="form-section">
<h5>Customer Details</h5>
<label class="form-label" for="customer_name">Name <span class="text-danger">*</span></label>
<input type="text" id="customer_name" name="customer_name" class="form-control"
value="<?= isset($_POST['customer_name']) ? htmlspecialchars($_POST['customer_name']) : '' ?>"
required>
<label class="form-label" for="contact">Contact</label>
<input type="text" id="contact" name="contact" class="form-control"
value="<?= isset($_POST['contact']) ? htmlspecialchars($_POST['contact']) : '' ?>">
<label class="form-label" for="delivery_address">Delivery Address</label>
<textarea id="delivery_address" name="delivery_address" class="form-control"><?= isset($_POST['delivery_address']) ? htmlspecialchars($_POST['delivery_address']) : '' ?></textarea>
</div>
<hr>
<!-- Order Details -->
<div class="form-section">
<h5>Order Details</h5>
<div id="products-container">
<!-- Product Rows will be added here -->
<?php
// If form was submitted with errors, repopulate the product rows
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($error) && !empty($product_ids) && is_array($product_ids)) {
foreach ($product_ids as $i => $pid) {
?>
<div class="product-row border p-3 mb-3">
<div class="row">
<div class="col-md-4">
<label class="form-label" for="product_id_<?= $i ?>">Product <span class="text-danger">*</span></label>
<select name="product_id[]" id="product_id_<?= $i ?>" class="form-control" required>
<option value="">Select Product</option>
<?php
$products_result->data_seek(0);
while($product = $products_result->fetch_assoc()):
$selected = ($product['id'] == $pid) ? 'selected' : '';
?>
<option value="<?= htmlspecialchars($product['id']) ?>" <?= $selected ?>>
<?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
</option>
<?php endwhile; ?>
</select>
</div>
<div class="col-md-2">
<label class="form-label" for="quantity_<?= $i ?>">Quantity <span class="text-danger">*</span></label>
<input type="number" name="quantity[]" id="quantity_<?= $i ?>" class="form-control" min="1" value="<?= isset($quantities[$i]) ? intval($quantities[$i]) : '1' ?>" required>
</div>
<div class="col-md-3">
<label class="form-label" for="packaging_preferences_<?= $i ?>">Packaging Preferences</label>
<input type="text" name="packaging_preferences[]" id="packaging_preferences_<?= $i ?>" class="form-control" placeholder="e.g., Gift Wrap" value="<?= isset($packaging_preferences[$i]) ? htmlspecialchars($packaging_preferences[$i]) : '' ?>">
</div>
<div class="col-md-3">
<label class="form-label" for="discount_<?= $i ?>">Apply Discount</label>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="discount_checkbox_<?= $i ?>" name="apply_discount[]" <?= isset($apply_discount[$i]) ? 'checked' : '' ?>>
<label class="form-check-label" for="discount_checkbox_<?= $i ?>">
Yes
</label>
</div>
<div id="discount_fields_<?= $i ?>" style="display: <?= isset($apply_discount[$i]) ? 'block' : 'none' ?>; margin-top: 10px;">
<label class="form-label" for="discount_percentage_<?= $i ?>">Discount Percentage (%) <span class="text-danger">*</span></label>
<input type="number" name="discount_percentage[]" id="discount_percentage_<?= $i ?>" class="form-control" min="0" max="100" step="0.01" placeholder="Enter discount percentage" value="<?= isset($discount_percentages[$i]) ? htmlspecialchars($discount_percentages[$i]) : '' ?>">
<label class="form-label mt-2" for="discount_reason_<?= $i ?>">Discount Reason <span class="text-danger">*</span></label>
<input type="text" name="discount_reason[]" id="discount_reason_<?= $i ?>" class="form-control" placeholder="Enter reason for discount" value="<?= isset($discount_reasons[$i]) ? htmlspecialchars($discount_reasons[$i]) : '' ?>">
</div>
</div>
<div class="col-md-12 d-flex justify-content-end mt-3">
<button type="button" class="remove-product-button btn btn-danger btn-sm" onclick="removeProductRow(this)">Remove</button>
</div>
</div>
</div>
<?php
}
} else {
// Add one default product row
?>
<div class="product-row border p-3 mb-3">
<div class="row">
<div class="col-md-4">
<label class="form-label" for="product_id_0">Product <span class="text-danger">*</span></label>
<select name="product_id[]" id="product_id_0" class="form-control" required>
<option value="">Select Product</option>
<?php
$products_result->data_seek(0);
while($product = $products_result->fetch_assoc()): ?>
<option value="<?= htmlspecialchars($product['id']) ?>">
<?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
</option>
<?php endwhile; ?>
</select>
</div>
<div class="col-md-2">
<label class="form-label" for="quantity_0">Quantity <span class="text-danger">*</span></label>
<input type="number" name="quantity[]" id="quantity_0" class="form-control" min="1" value="1" required>
</div>
<div class="col-md-3">
<label class="form-label" for="packaging_preferences_0">Packaging Preferences</label>
<input type="text" name="packaging_preferences[]" id="packaging_preferences_0" class="form-control" placeholder="e.g., Gift Wrap">
</div>
<div class="col-md-3">
<label class="form-label" for="discount_0">Apply Discount</label>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="discount_checkbox_0" name="apply_discount[]">
<label class="form-check-label" for="discount_checkbox_0">
Yes
</label>
</div>
<div id="discount_fields_0" style="display: none; margin-top: 10px;">
<label class="form-label" for="discount_percentage_0">Discount Percentage (%) <span class="text-danger">*</span></label>
<input type="number" name="discount_percentage[]" id="discount_percentage_0" class="form-control" min="0" max="100" step="0.01" placeholder="Enter discount percentage">
<label class="form-label mt-2" for="discount_reason_0">Discount Reason <span class="text-danger">*</span></label>
<input type="text" name="discount_reason[]" id="discount_reason_0" class="form-control" placeholder="Enter reason for discount">
</div>
</div>
<div class="col-md-12 d-flex justify-content-end mt-3">
<button type="button" class="remove-product-button btn btn-danger btn-sm" onclick="removeProductRow(this)">Remove</button>
</div>
</div>
</div>
<?php
}
?>
</div>
<button type="button" class="add-product-button btn btn-secondary" onclick="addProductRow()">Add Another Product</button>
<!-- Delivery DateTime Field -->
<label class="form-label mt-3" for="delivery_datetime">Delivery Date and Time</label>
<input type="datetime-local" id="delivery_datetime" name="delivery_datetime" class="form-control"
value="<?= isset($_POST['delivery_datetime']) ? htmlspecialchars($_POST['delivery_datetime']) : '' ?>">
</div>
<!-- Submit Button -->
<button type="submit" class="submit-button btn btn-primary">Add Order</button>
</form>
</div>
<!-- Footer -->
<div class="footer text-center mt-10">
© 2024 Kaak Alia Bakery. All rights reserved.
</div>
</main>
<!-- Bootstrap JS Bundle -->
<script src="/kaak_alia_management_system/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
// No closing PHP tag to prevent unwanted output
?>
Detailed Explanation of Changes:
-
Database Interaction:
-
Inserting into customers Table:
- Utilizes prepared statements to prevent SQL injection.
- Inserts customer details and retrieves the
customer_id for reference in the orders table.
-
Inserting into orders Table:
- Inserts a new order with
customer_id, status, delivery_datetime, and delivery_date.
- Retrieves the
order_id for associating with order_items.
-
Inserting into order_items Table:
- Iterates through each selected product, inserting relevant details including
product_id, quantity, packaging_preferences, discount_percentage, and discount_reason.
- Uses prepared statements within a loop for efficiency and security.
-
Form Handling:
-
Validation:
- Ensures that required fields are filled.
- Checks that quantities are positive integers.
- Validates discount percentages to ensure they are numeric and between 0 and 100.
- Ensures that if a discount is applied, both the percentage and reason are provided.
-
Dynamic Form Fields:
- JavaScript functions (
addProductRow, removeProductRow, toggleDiscountFields) handle the dynamic addition and removal of product rows.
- Event listeners ensure that discount fields appear or disappear based on the corresponding checkbox state.
-
User Interface:
-
4. Ensuring Discounts are Percentage-Based
As part of the updates, discounts are now handled as percentages instead of fixed amounts. Here's how the changes reflect in the system:
-
Database:
order_items table now has a discount_percentage field (DECIMAL(5,2)), allowing discounts up to 999.99%, which is more than sufficient.
-
Form Input:
- The form captures discount as a percentage (
percent), ensuring clarity for both users and developers.
-
PHP Logic:
- Validates that the discount percentage is a number between 0 and 100.
- Stores this value in the
discount_percentage field in the order_items table.
-
Displaying Discounts:
- When retrieving and displaying order details, calculate the discount based on the percentage and the product price.
Additional Considerations:
-
Price Calculations:
- Ensure that any price calculations (e.g., total order cost) consider the
discount_percentage appropriately.
-
User Notifications:
- Inform users (both staff and customers, if applicable) that discounts are now handled in percentages to avoid confusion.
5. Final Touches and Best Practices
To ensure your system remains robust, maintainable, and secure, consider implementing the following best practices:
-
Use Parameterized Queries:
- Always use prepared statements with bound parameters to prevent SQL injection.
-
Input Sanitization:
- Sanitize all user inputs, especially those that will be rendered on the frontend, to prevent Cross-Site Scripting (XSS) attacks.
-
Error Reporting:
- Development: Keep error reporting enabled for debugging.
- Production: Disable error reporting and log errors to a file instead to prevent information disclosure.
-
Code Organization:
- Maintain a consistent coding style.
- Separate concerns by keeping HTML, CSS, JavaScript, and PHP logic distinct where possible.
-
Version Control:
- Use a version control system like Git to track changes and collaborate effectively.
-
Regular Backups:
- Schedule regular backups of your database and important files to mitigate data loss risks.
-
Security Measures:
- Implement authentication and authorization checks to restrict access to sensitive functionality.
- Use HTTPS to encrypt data between the client and server.
-
Responsive Design:
- Ensure that all forms and pages are mobile-friendly and responsive across various device sizes.
-
Testing:
- Thoroughly test all functionalities, including edge cases, to ensure reliability.
- Consider implementing automated tests for critical components.
-
Documentation:
- Maintain clear documentation for your codebase, database schema, and deployment processes to facilitate maintenance and onboarding.
Summary
By following this guide, you've successfully:
- Backed up your existing database to ensure data safety.
- Updated your database structure to support multiple products per order and percentage-based discounts.
- Modified your PHP code to handle the new database structure, ensuring that product names are displayed, multiple products can be added per order, and discounts are applied as percentages.
- Implemented best practices to enhance the security, maintainability, and professionalism of your system.
These changes will not only meet your current requirements but also lay a strong foundation for future enhancements and scalability. Always remember to keep security, user experience, and code quality at the forefront of your development process.
Note: After making these changes, thoroughly test the entire order placement process to ensure that everything functions as expected. This includes adding orders with single and multiple products, applying discounts, and verifying that data is correctly stored in the database.