prepare("SELECT * FROM products WHERE product_id = ?"); $stmt->execute([$product_id]); $product = $stmt->fetch(); if (!$product) { header('Location: index.php'); exit; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $name = trim($_POST['name']); $description = trim($_POST['description']); $price = floatval($_POST['price']); $stock = intval($_POST['stock']); $category = trim($_POST['category']); $subcategory = isset($_POST['subcategory']) ? trim($_POST['subcategory']) : ''; $size = isset($_POST['size']) ? trim($_POST['size']) : null; // Validate input if (empty($name) || empty($description) || $price <= 0 || $stock < 0) { $error_message = "Please fill in all required fields correctly."; } else { // Handle image upload $image = $product['image']; if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) { $upload_dir = '../../uploads/products/'; if (!file_exists($upload_dir)) { mkdir($upload_dir, 0777, true); } $file_extension = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION)); $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif']; if (in_array($file_extension, $allowed_extensions)) { // Delete old image if exists if (!empty($product['image'])) { $old_image_path = $upload_dir . $product['image']; if (file_exists($old_image_path)) { unlink($old_image_path); } } $image = uniqid() . '.' . $file_extension; $upload_path = $upload_dir . $image; if (!move_uploaded_file($_FILES['image']['tmp_name'], $upload_path)) { $error_message = "Failed to upload image."; } } else { $error_message = "Invalid image format. Allowed formats: JPG, JPEG, PNG, GIF"; } } if (empty($error_message)) { try { $stmt = $pdo->prepare(" UPDATE products SET name = ?, description = ?, price = ?, stock = ?, category = ?, subcategory = ?, size = ?, image = ? WHERE product_id = ? "); $stmt->execute([ $name, $description, $price, $stock, $category, $subcategory, $size, $image, $product_id ]); $success_message = "Product updated successfully!"; // Refresh product data $stmt = $pdo->prepare("SELECT * FROM products WHERE product_id = ?"); $stmt->execute([$product_id]); $product = $stmt->fetch(); } catch (PDOException $e) { $error_message = "Error updating product: " . $e->getMessage(); } } } } ?> Edit Product - Admin Dashboard
Back to Products

Edit Product

Current product image
Image preview