34567-vm/products/update.php
2025-10-02 20:43:00 +00:00

49 lines
1.4 KiB
PHP

<?php
require_once __DIR__ . '/../db/config.php';
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method Not Allowed']);
exit;
}
$data = json_decode(file_get_contents('php://input'), true);
if (empty($data['id'])) {
http_response_code(400);
echo json_encode(['error' => 'Missing required field: id']);
exit;
}
$id = $data['id'];
// Fetch the existing product to see which fields are being updated
$pdo = db();
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$id]);
$product = $stmt->fetch();
if (!$product) {
http_response_code(404);
echo json_encode(['error' => 'Product not found']);
exit;
}
$name = $data['name'] ?? $product['name'];
$description = $data['description'] ?? $product['description'];
$price = $data['price'] ?? $product['price'];
$cost = $data['cost'] ?? $product['cost'];
$quantity = $data['quantity'] ?? $product['quantity'];
try {
$stmt = $pdo->prepare("UPDATE products SET name = ?, description = ?, price = ?, cost = ?, quantity = ? WHERE id = ?");
$stmt->execute([$name, $description, $price, $cost, $quantity, $id]);
echo json_encode(['message' => 'Product updated successfully']);
} catch (PDOException $e) {
http_response_code(500);
echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}