null,
'name' => '',
'description' => '',
'price' => '',
'image' => ''
];
$errors = [];
$page_title = 'Add New Product';
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$page_title = 'Edit Product';
$product_id = $_GET['id'];
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$product_id]);
$product = $stmt->fetch();
if (!$product) {
header("Location: admin_products.php");
exit;
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$product['name'] = $_POST['name'];
$product['description'] = $_POST['description'];
$product['price'] = $_POST['price'];
$product['image'] = $_POST['image'];
if (empty($product['name'])) {
$errors[] = 'Name is required';
}
if (empty($product['price']) || !is_numeric($product['price'])) {
$errors[] = 'Price must be a number';
}
if (empty($errors)) {
if ($product['id']) {
// Update
$stmt = $pdo->prepare("UPDATE products SET name = ?, description = ?, price = ?, image = ? WHERE id = ?");
$stmt->execute([$product['name'], $product['description'], $product['price'], $product['image'], $product['id']]);
} else {
// Insert
$stmt = $pdo->prepare("INSERT INTO products (name, description, price, image) VALUES (?, ?, ?, ?)");
$stmt->execute([$product['name'], $product['description'], $product['price'], $product['image']]);
}
header("Location: admin_products.php");
exit;
}
}
?>