<?
php
include 'db_connect.php';
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Sanitize input
function clean($data) {
return htmlspecialchars(trim($data));
}
// Handle Add / Update
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$product_name = clean($_POST['product_name']);
$sku = clean($_POST['sku']);
$category_id = !empty($_POST['category_id']) ? intval($_POST['category_id']) :
null;
$unit_price = floatval($_POST['unit_price']);
$quantity = intval($_POST['quantity']);
$description = clean($_POST['description']);
if (isset($_POST['product_id']) && $_POST['product_id'] > 0) {
// Update product
$stmt = $conn->prepare("UPDATE products SET product_name=?, sku=?,
category_id=?, unit_price=?, quantity=?, description=? WHERE product_id=?");
$stmt->bind_param("ssiddsi", $product_name, $sku, $category_id,
$unit_price, $quantity, $description, $_POST['product_id']);
$stmt->execute();
$stmt->close();
} else {
// Insert new product
$stmt = $conn->prepare("INSERT INTO products (product_name, sku,
category_id, unit_price, quantity, description) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssiddi", $product_name, $sku, $category_id, $unit_price,
$quantity, $description);
$stmt->execute();
$stmt->close();
}
}
// Handle Delete
if (isset($_GET['delete'])) {
$product_id = intval($_GET['delete']);
$stmt = $conn->prepare("DELETE FROM products WHERE product_id=?");
$stmt->bind_param("i", $product_id);
$stmt->execute();
$stmt->close();
}
// Redirect back to form
header("Location: product_form.html");
exit;
?>