prepare("SELECT * FROM products WHERE id = ?"); $stmt->execute([$id]); $product = $stmt->fetch(); if(!$product) { header("Location: products.php"); exit; } // --- 4. FETCH CATEGORIES (For Dropdown) --- try { $catStmt = $pdo->query("SELECT * FROM categories WHERE status = 1 ORDER BY name ASC"); $categories = $catStmt->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $e) { $categories = []; } // --- 5. HANDLE UPDATE --- $msg = ""; $msg_type = ""; if(isset($_POST['update_product'])) { $title = trim($_POST['title']); $category = $_POST['category']; // <--- Category Update $price = $_POST['price']; $desc = $_POST['description']; // Update Text Fields (Added Category Column) $sql = "UPDATE products SET title=?, category=?, price=?, description=? WHERE id=?"; $pdo->prepare($sql)->execute([$title, $category, $price, $desc, $id]); // 1. Update Image if selected if(!empty($_FILES['image']['name'])) { $img_name = time() . '_' . $_FILES['image']['name']; move_uploaded_file($_FILES['image']['tmp_name'], "../uploads/products/" . $img_name); // Delete old image if(!empty($product['image']) && file_exists("../uploads/products/".$product['image'])) { @unlink("../uploads/products/".$product['image']); } $pdo->prepare("UPDATE products SET image=? WHERE id=?")->execute([$img_name, $id]); } // 2. Update File if selected if(!empty($_FILES['file']['name'])) { $file_name = time() . '_' . $_FILES['file']['name']; move_uploaded_file($_FILES['file']['tmp_name'], "../uploads/files/" . $file_name); $file_dest = "uploads/files/" . $file_name; // DB Path // Delete old file if(!empty($product['file_path']) && file_exists("../".$product['file_path'])) { @unlink("../".$product['file_path']); } $pdo->prepare("UPDATE products SET file_path=? WHERE id=?")->execute([$file_dest, $id]); } $msg = "Product updated successfully!"; $msg_type = "success"; // Refresh Data for View $stmt->execute([$id]); $product = $stmt->fetch(); } ?>