prepare("SELECT COUNT(*) FROM deals WHERE contact_id = :contact_id"); $stmt->bindParam(':contact_id', $contact_id, PDO::PARAM_INT); $stmt->execute(); $deal_count = $stmt->fetchColumn(); if ($deal_count > 0) { $_SESSION['error_message'] = "Cannot delete contact. It is associated with {$deal_count} deal(s). Please reassign or delete the deals first."; } else { // No associated deals, proceed with deletion $stmt = $pdo->prepare("DELETE FROM contacts WHERE id = :id"); $stmt->bindParam(':id', $contact_id, PDO::PARAM_INT); if ($stmt->execute() && $stmt->rowCount() > 0) { $_SESSION['success_message'] = "Contact deleted successfully."; } else { $_SESSION['error_message'] = "Failed to delete contact or contact not found."; } } } catch (PDOException $e) { $_SESSION['error_message'] = "Database error: " . $e->getMessage(); } header("Location: contacts.php"); exit; ?>