35512-vm/delete-category.php
2025-11-08 20:43:02 +00:00

44 lines
1.0 KiB
PHP

<?php
session_start();
require_once 'db/config.php';
require_once 'auth-check.php';
require_once 'auth-helpers.php';
if (!can($_SESSION['user_role_id'], 'category', 'delete')) {
header('Location: index.php?error=access_denied');
exit;
}
$category_id = $_GET['id'] ?? null;
if (!$category_id) {
header('Location: categories.php');
exit;
}
try {
$pdo = db();
$pdo->beginTransaction();
// Set category_id to NULL for assets associated with this category
$stmt = $pdo->prepare('UPDATE assets SET category_id = NULL WHERE category_id = ?');
$stmt->execute([$category_id]);
// Delete the category
$stmt = $pdo->prepare('DELETE FROM categories WHERE id = ?');
$stmt->execute([$category_id]);
$pdo->commit();
header("Location: categories.php?success=category_deleted");
exit;
} catch (PDOException $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
// In a real app, log this error.
header("Location: categories.php?error=db_error");
exit;
}