in this codes (<?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);
// Include authentication and database connection before including the header
require_once DIR . '/../../includes/auth.php';
require_once DIR . '/../../includes/db_connect.php';
// Now include the header
require_once '../../includes/header.php';
// Initialize variables
success=′′;error = '';
// Fetch products for selection
products_result = products_sql);
Assistant
productssql="SELECT∗FROMproductsORDERBYnameASC";
conn−>query(
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[′customername′]);contact = trim(POST[′contact′]);delivery_address = trim(POST[′deliverydelivery_datetime = isset(_POST['delivery_datetime']) && !empty(_POST['delivery_datetime']) ? trim($_POST['delivery_datetime']) : null;
code
// 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'] : [];
// 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 ($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
// Retain the first product in the orders table's product_id
$first_product_id = intval($product_ids[0]);
$first_quantity = intval($quantities[0]);
$first_packaging_preferences = trim($packaging_preferences[0]);
$stmt = $conn->prepare("INSERT INTO orders (customer_id, product_id, quantity, packaging_preferences, status, order_date, delivery_datetime) VALUES (?, ?, ?, ?, 'Pending', NOW(), ?)");
if (!$stmt) {
throw new Exception("Prepare statement failed: " . $conn->error);
}
$stmt->bind_param("iiiss", $customer_id, $first_product_id, $first_quantity, $first_packaging_preferences, $delivery_datetime);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
$order_id = $stmt->insert_id;
$stmt->close();
// Insert remaining products into order_items table
if (count($product_ids) > 1) {
$stmt = $conn->prepare("INSERT INTO order_items (order_id, product_id, quantity, packaging_preferences) VALUES (?, ?, ?, ?)");
if (!$stmt) {
throw new Exception("Prepare statement failed: " . $conn->error);
}
// Loop through remaining products (starting from index 1)
for ($i = 1; $i < count($product_ids); $i++) {
$pid = intval($product_ids[$i]);
$qty = intval($quantities[$i]);
$pack_pref = trim($packaging_preferences[$i]);
$stmt->bind_param("iiis", $order_id, $pid, $qty, $pack_pref);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
}
$stmt->close();
}
// Commit transaction
$conn->commit();
$success = "Order added successfully!";
// Reset form fields
$_POST = [];
} catch (Exception $e) {
// Rollback transaction
$conn->rollback();
$error = "Error adding order: " . $e->getMessage();
}
}
It sounds like you're experiencing an issue where clicking the "Add Order" button on your add_order.php page unexpectedly redirects you to view_orders.php and displays raw PHP code instead of executing it. This behavior can stem from several potential causes, including form configuration issues, server misconfigurations, or unintended redirects in your code. Let's walk through a systematic approach to diagnose and resolve this problem.
action="": This means the form is submitted to the same page (add_order.php).
Potential Issue:
If the form is unintentionally redirecting to view_orders.php, it's crucial to confirm that:
The action attribute isn't being altered elsewhere in your code or included files.
There are no JavaScript events overriding the form submission behavior.
Action Steps:
Check for JavaScript Overrides:
Ensure there's no JavaScript (either inline or in included scripts) that intercepts the form submission and redirects to view_orders.php.
Review Included Files (header.php, auth.php):
Inspect header.php and any other included files for any redirects or form action manipulations that might point to view_orders.php.
Testing:
Temporarily set the form action to explicitly point to add_order.php to rule out any unintended alterations:
html
<form method="POST" action="add_order.php">
Observe if the behavior changes.
2. Inspect Server Configuration
Symptom:
Displaying raw PHP code typically indicates that the server isn't processing PHP files correctly.
Potential Causes:
PHP Not Installed or Misconfigured:
The server lacks PHP installation.
Incorrect PHP handler configuration in the server (e.g., Apache or Nginx).
File Permissions:
The server doesn't have the necessary permissions to execute PHP files.
Incorrect File Extension:
Ensure that your files have the .php extension and not .html or another format.
Action Steps:
Check PHP Installation:
Run a simple PHP file to test, such as info.php:
php
<?php phpinfo(); ?>
Navigate to info.php in your browser. If it displays PHP configuration details, PHP is working correctly. If it shows raw code, PHP isn't being processed.
Review Server Configuration:
For Apache:
Ensure that mod_php is enabled.
Verify the presence of the following in your Apache configuration:
Temporarily add a test message after each require_once to ensure files are included correctly:
php
require_once __DIR__ . '/../../includes/auth.php';
echo "Auth included successfully.";
8. Additional Recommendations
Use Relative URLs for Assets:
Instead of absolute paths like /kaak_alia_management_system/assets/..., consider using relative paths or dynamic URLs to prevent path issues across different environments.
Sanitize User Inputs:
While your current code uses htmlspecialchars() for output, ensure all inputs are properly sanitized and validated to prevent SQL injection and other security issues.
Implement CSRF Protection:
Consider adding CSRF tokens to your forms to enhance security.
User Feedback:
After a successful order addition, maintain consistency in user experience. Decide whether to stay on the add_order.php page with a success message or redirect to view_orders.php with an acknowledgment.
Summary
The issue where clicking "Add Order" redirects to view_orders.php and displays raw PHP code is likely due to one or a combination of the following:
Server Misconfiguration: PHP isn't being processed correctly, leading to raw code display.
Unintended Redirects: Code or included files redirecting form submissions improperly.
Form Action Issues: The form might be pointing to the wrong script upon submission.
By systematically verifying your form configuration, server setup, included files, and debugging the process, you can identify and resolve the root cause of the issue. If after following these steps the problem persists, consider providing additional details or error log excerpts for more targeted assistance.