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
--
-- Table structure for table customers
CREATE TABLE customers (
id int(11) NOT NULL,
name varchar(100) NOT NULL,
contact varchar(50) DEFAULT NULL,
delivery_address text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table orders
CREATE TABLE orders (
id int(11) NOT NULL,
customer_id int(11) NOT NULL,
product_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,
quantity int(11) NOT NULL DEFAULT 1,
packaging_preferences varchar(255) DEFAULT NULL,
discount_amount decimal(10,2) DEFAULT 0.00,
discount_reason varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table order_items
CREATE TABLE order_items (
id int(11) NOT NULL,
order_id int(11) NOT NULL,
product_id int(11) NOT NULL,
quantity int(11) NOT NULL,
packaging_preferences varchar(255) DEFAULT NULL,
discount_amount decimal(10,2) DEFAULT 0.00,
discount_reason varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table products
CREATE TABLE products (
id int(11) NOT NULL,
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
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table users
CREATE TABLE users (
id int(11) NOT NULL,
username varchar(50) NOT NULL,
password varchar(255) NOT NULL,
role enum('admin','staff') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE order_items
ADD CONSTRAINT order_items_ibfk_1 FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE,
ADD CONSTRAINT order_items_ibfk_2 FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE;
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 */;)
The error you're encountering occurs because the script attempts to delete a product even when it's referenced in the orders table. This is due to an issue in how the count of existing references is being fetched from the database. Specifically, the mysqli_stmt::bind_result function isn't correctly retrieving the count because the result set isn't being properly stored before binding.
Here's a detailed explanation and step-by-step solution to fix the issue:
Understanding the Issue
Error Message:
Fatal error: Uncaught mysqli_sql_exception: Cannot delete or update a parent row: a foreign key constraint fails (`u406552082_kaakalia`.`orders`, CONSTRAINT `orders_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`)) ...
This error indicates that you're trying to delete a product that's still referenced in the orders table, violating the foreign key constraint.
Current Delete Handling Logic:
elseif (isset($_POST['delete_product'])) {
$id = intval($_POST['id']);
// Check if the product is referenced in any orders
$check_sql = "SELECT COUNT(*) AS count FROM orders WHERE product_id = ?";
$stmt = $conn->prepare($check_sql);
if ($stmt) {
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();
if ($count > 0) {
$error = "Cannot delete product because it is associated with existing orders.";
} else {
// Proceed to delete the product
$delete_sql = "DELETE FROM products WHERE id = ?";
$stmt = $conn->prepare($delete_sql);
if ($stmt) {
$stmt->bind_param("i", $id);
if ($stmt->execute()) {
$success = "Product deleted successfully!";
} else {
$error = "Error deleting product: " . $stmt->error;
}
$stmt->close();
} else {
$error = "Prepare statement failed: " . $conn->error;
}
}
} else {
$error = "Prepare statement failed: " . $conn->error;
}
}
The intention here is to prevent deletion if the product is referenced in the orders table. However, the check isn't working as expected because the COUNT(*) isn't being correctly fetched due to missing store_result().
Solution
1. Properly Fetch the COUNT Result
When using mysqli prepared statements, it's essential to store the result before binding and fetching. This ensures that the result set is available for binding.
Update the Delete Handling Logic:
elseif (isset($_POST['delete_product'])) {
$id = intval($_POST['id']);
// Check if the product is referenced in any orders
$check_sql = "SELECT COUNT(*) AS count FROM orders WHERE product_id = ?";
$stmt = $conn->prepare($check_sql);
if ($stmt) {
$stmt->bind_param("i", $id);
$stmt->execute();
// Store the result to ensure bind_result works correctly
$stmt->store_result();
$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();
if ($count > 0) {
$error = "Cannot delete product because it is associated with existing orders.";
} else {
// Proceed to delete the product
$delete_sql = "DELETE FROM products WHERE id = ?";
$stmt = $conn->prepare($delete_sql);
if ($stmt) {
$stmt->bind_param("i", $id);
if ($stmt->execute()) {
$success = "Product deleted successfully!";
} else {
$error = "Error deleting product: " . $stmt->error;
}
$stmt->close();
} else {
$error = "Prepare statement failed: " . $conn->error;
}
}
} else {
$error = "Prepare statement failed: " . $conn->error;
}
}
Explanation:
$stmt->store_result();: This function stores the result set in the statement handle, enabling bind_result to function correctly.
Ensures Accurate COUNT(*): With the result stored, bind_result can now accurately fetch the count of references, preventing the script from erroneously deleting products that are still referenced.
2. (Optional) Check Both orders and order_items Tables
Given your database schema, the order_items table also references the products table. While order_items uses ON DELETE CASCADE, it's good practice to ensure all references are accounted for, especially if you're enforcing deletion restrictions in the orders table.
Enhanced Check to Include Both Tables:
elseif (isset($_POST['delete_product'])) {
$id = intval($_POST['id']);
// Check if the product is referenced in any orders or order_items
$check_sql = "
SELECT
(SELECT COUNT(*) FROM orders WHERE product_id = ?) +
(SELECT COUNT(*) FROM order_items WHERE product_id = ?) AS total_count
";
$stmt = $conn->prepare($check_sql);
if ($stmt) {
$stmt->bind_param("ii", $id, $id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($total_count);
$stmt->fetch();
$stmt->close();
if ($total_count > 0) {
$error = "Cannot delete product because it is associated with existing orders or order items.";
} else {
// Proceed to delete the product
$delete_sql = "DELETE FROM products WHERE id = ?";
$stmt = $conn->prepare($delete_sql);
if ($stmt) {
$stmt->bind_param("i", $id);
if ($stmt->execute()) {
$success = "Product deleted successfully!";
} else {
$error = "Error deleting product: " . $stmt->error;
}
$stmt->close();
} else {
$error = "Prepare statement failed: " . $conn->error;
}
}
} else {
$error = "Prepare statement failed: " . $conn->error;
}
}
Explanation:
Aggregated Count: This query sums the counts from both orders and order_items, ensuring comprehensive reference checking.
Error Message: Updated to reflect references from both tables.
3. Ensure Foreign Key Constraints are Correct
While your PHP code is responsible for preventing deletions that violate constraints, ensuring foreign keys are correctly set up adds an additional layer of data integrity.
Consistency in Deletion Rules: Decide whether you want deletions in products to cascade to both orders and order_items or restrict them. Currently, order_items are set to ON DELETE CASCADE, which might automatically delete related order_items when a product is deleted. However, orders are set to restrict deletions if related products exist.
Avoid Mixed Behaviors: For clarity and predictability, it's often better to have consistent foreign key behaviors across related tables unless there's a specific reason for differing behaviors.
Final Revised manage_products.php
Here's the complete revised portion of your manage_products.php file with the necessary fixes:
<?php
// ... [previous code remains unchanged]
// Delete Product
elseif (isset($_POST['delete_product'])) {
$id = intval($_POST['id']);
// Check if the product is referenced in any orders
$check_sql = "SELECT COUNT(*) AS count FROM orders WHERE product_id = ?";
$stmt = $conn->prepare($check_sql);
if ($stmt) {
$stmt->bind_param("i", $id);
$stmt->execute();
// Store the result to ensure bind_result works correctly
$stmt->store_result();
$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();
if ($count > 0) {
$error = "Cannot delete product because it is associated with existing orders.";
} else {
// Proceed to delete the product
$delete_sql = "DELETE FROM products WHERE id = ?";
$stmt = $conn->prepare($delete_sql);
if ($stmt) {
$stmt->bind_param("i", $id);
if ($stmt->execute()) {
$success = "Product deleted successfully!";
} else {
$error = "Error deleting product: " . $stmt->error;
}
$stmt->close();
} else {
$error = "Prepare statement failed: " . $conn->error;
}
}
} else {
$error = "Prepare statement failed: " . $conn->error;
}
}
// ... [rest of the code remains unchanged]
?>
Additional Recommendations
Use Parameterized Queries Consistently:
Ensure all database interactions use prepared statements to prevent SQL injection.
Error Handling:
Consider logging errors to a file instead of displaying them, especially in a production environment.
Use more granular error messages to aid in debugging without exposing sensitive information.
User Feedback:
After successful deletion, you might want to redirect the user or update the product list dynamically.
Provide clearer messages or modals to inform the user about the deletion status.
Database Integrity:
Regularly review foreign key constraints to ensure they align with your application's logic.
Consider cascading deletions only when it makes sense for your data model.
Code Refactoring:
Organize repetitive tasks into reusable functions or classes.
Separate business logic from presentation to enhance maintainability.
By implementing these changes, your script should correctly prevent the deletion of products that are still referenced in the orders table, thereby avoiding the foreign key constraint errors you've been experiencing.