34849-vm/delete_product.php
2026-02-03 01:43:03 +00:00

43 lines
1.4 KiB
PHP

<?php
session_start();
header('Content-Type: application/json');
// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
echo json_encode(['success' => false, 'error' => 'No autorizado']);
exit;
}
require_once 'db/config.php';
$response = ['success' => false, 'error' => 'Petición inválida'];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$productId = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
if ($productId > 0) {
try {
$db = db();
$stmt = $db->prepare("DELETE FROM products WHERE id = :id");
$stmt->bindParam(':id', $productId, PDO::PARAM_INT);
if ($stmt->execute()) {
if ($stmt->rowCount() > 0) {
$response = ['success' => true];
} else {
$response['error'] = 'El producto no fue encontrado o ya fue eliminado.';
}
} else {
$response['error'] = 'Error al ejecutar la consulta de eliminación.';
}
} catch (PDOException $e) {
// Log error to a file in a real application
// error_log($e->getMessage());
$response['error'] = 'Error de base de datos: ' . $e->getMessage();
}
} else {
$response['error'] = 'ID de producto inválido.';
}
}
echo json_encode($response);