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();
}
}
Based on the provided add_order.php code, the form submission should process the order and display a success or error message on the same page. However, you've observed that clicking the "Add Order" button redirects you to public/orders/view_orders.php. This unexpected behavior isn't directly caused by the code you've shared but likely results from one of the following factors:
Redirects in Included Files: The add_order.php script includes three files before rendering the HTML:
auth.php
db_connect.php
header.php
It's possible that one of these files, especially header.php, contains a redirect to view_orders.php.
Server-Side Configuration: Your server might have routing rules or configurations that redirect form submissions from add_order.php to view_orders.php.
JavaScript Redirects: There might be JavaScript within the included files or elsewhere on the page that triggers a redirect upon form submission.
Form Action Misconfiguration: Although the action attribute in your form is set to an empty string (action=""), which typically submits the form to the same page, there might be other factors influencing the redirection.
Steps to Diagnose and Resolve the Issue
Check Included Files for Redirects:
auth.php and db_connect.php: Review these files to ensure they don't contain any header("Location: ...") statements or other redirect logic.
header.php: This is the most likely culprit. Open header.php and look for any redirect logic. If you find something like header("Location: view_orders.php");, you'll need to adjust or remove it based on your application's flow.
php
// Example of a redirect in header.php
// Remove or conditionally execute this
header("Location: view_orders.php");
exit;
Explicitly Set the Form Action:
Instead of leaving the action attribute empty, explicitly point it to add_order.php to ensure the form submits to the correct page.
html
<form method="POST" action="add_order.php">
Inspect JavaScript for Redirects:
Search through all JavaScript code (both inline and external) for any window.location, window.location.href, or similar statements that might redirect the page after form submission.
Specifically, check within header.php or other included scripts for such logic.
javascript
// Example of a JavaScript redirect
window.location.href = 'view_orders.php';
Use Browser Developer Tools:
Network Tab: Open the Developer Tools (usually by pressing F12 or Ctrl+Shift+I) and navigate to the Network tab. Submit the form and observe the network requests to see where the submission is being sent and if a redirect occurs.
Console Tab: Look for any JavaScript errors or logs that might indicate why the redirect is happening.
Add Debugging Statements:
Temporarily insert debugging statements in add_order.php to confirm that the form submission is reaching the correct script.
php
<?php
// At the very top of add_order.php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "Form submission received.";
// Optionally, log to a file
file_put_contents('debug.log', "Form submitted at " . date('Y-m-d H:i:s') . "\n", FILE_APPEND);
}
?>
If you don't see these messages, it's a sign that the form isn't submitting to add_order.php as intended.
Review Server Routing Rules:
If you're using a framework or have custom server routing (like .htaccess rules), ensure that there's no rule inadvertently redirecting add_order.php to view_orders.php.
apache
# Example of a .htaccess rule that redirects add_order.php to view_orders.php
RewriteRule ^public/orders/add_order\.php$ /public/orders/view_orders.php [R=301,L]
Ensure that such rules are not in place or are correctly configured.
Check for Form Submission via AJAX:
If any JavaScript in the included files handles form submissions via AJAX, ensure that the AJAX request targets add_order.php and handles the response appropriately without redirecting.
javascript
// Example of an AJAX submission that might redirect
$.post('add_order.php', $('#order-form').serialize(), function(response) {
if (response.success) {
window.location.href = 'view_orders.php';
}
}, 'json');
Modify or remove any such redirection logic if it's not desired.
Ensure Proper Form Structure:
Verify that your form isn't nested within another form or that there are no overlapping form tags that might cause unexpected behavior.
html
<!-- Correct Form Structure -->
<form method="POST" action="add_order.php">
<!-- Form fields -->
</form>
Avoid nested forms or missing closing tags.
PHP Output Before Headers:
Ensure that there's no output (like echoed content) before any header("Location: ...") calls, as this can cause PHP to send headers prematurely and lead to unexpected behavior.
php
<?php
// Correct Usage
if ($condition) {
header("Location: view_orders.php");
exit;
}
// No output before this
?>
Example Adjusted Code
Assuming that the issue is within header.php, here's how you might adjust your add_order.php:
Modify the header.php to Remove Unnecessary Redirects:
Ensure header.php only contains HTML head elements, navigation, etc., without any redirect logic.
php
<!-- header.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Head content like meta tags, title, CSS links -->
</head>
<body>
<!-- Navigation bar or header content -->
Remove Duplicate HTML Tags in add_order.php:
Since header.php already contains <html>, <head>, and <body>, you don't need to include them again in add_order.php.
Consistent HTML Structure: Ensure that your included files (header.php, footer.php, etc.) maintain a consistent and non-overlapping HTML structure. Avoid duplicating <html>, <head>, or <body> tags.
Debug Incrementally: Start by simplifying your add_order.php to the bare minimum and ensure it works without redirection. Gradually add back the included files and additional logic to identify where the redirect originates.
Check Server Logs: Review your server's error logs to see if any unexpected errors or redirects are being triggered during form submission.
Use Version Control: If you're using Git or another version control system, review recent changes to identify when the redirect behavior was introduced.
By systematically checking each potential source of the redirect and ensuring your HTML structure is correct, you should be able to identify and resolve the issue causing the form to redirect to view_orders.php.
Note: Ensure that the HTML structure is not duplicated. If header.php includes the opening <html>, <head>, and <body> tags, your add_order.php should not re-declare them.
Ensure No Redirects in header.php:
Example header.php without redirects:
php
<!-- header.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Kaak Alia Management System</title>
<!-- Include CSS and other head elements -->
</head>
<body>
<!-- Navigation bar or header content -->
If you need to conditionally redirect after form submission, handle it within add_order.php after processing the form.
Optionally, Add Redirect After Successful Submission:
If you prefer to redirect to view_orders.php after successfully adding an order, you can add a redirect in your form processing logic.
php
if (empty($error)) {
// [Database operations]
if ($operation_successful) {
// Redirect to view orders
header("Location: view_orders.php?success=1");
exit;
}
}
This approach replaces the success message with a redirect, providing a clearer user flow.