JIT
Getting ready for something exciting!
Updated files
v1
fix this code, every time i click "Add DEpartment" the department u want to add is not being added, it seems like its not being procees: <?php session_start(); date_default_timezone_set('Asia/Manila'); global $wpdb; // Database table names $dept_table_name = 'departments'; $user_table_name = 'users'; $message = ''; $message_type = ''; // Handle success messages from redirect if (isset($_GET['message'])) { if ($_GET['message'] === 'updated') { $message = 'Department updated successfully!'; $message_type = 'success'; } elseif ($_GET['message'] === 'added') { $message = 'Department added successfully!'; $message_type = 'success'; } } // --- Handle delete department action --- if (isset($_GET['action']) && $_GET['action'] === 'delete_dept' && isset($_GET['id']) && isset($_GET['_wpnonce']) && wp_verify_nonce($_GET['_wpnonce'], 'delete_dept_' . absint($_GET['id']))) { $dept_id_to_delete = absint($_GET['id']); if ($dept_id_to_delete) { // Check if department has users $users_count = $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM $user_table_name WHERE department_id = %d", $dept_id_to_delete )); if ($users_count > 0) { $message = 'Cannot delete department with assigned users.'; $message_type = 'error'; } else { $deleted = $wpdb->delete( $dept_table_name, ['id' => $dept_id_to_delete], ['%d'] ); if ($deleted) { $message = 'Department deleted successfully!'; $message_type = 'success'; } else { $message = 'Error deleting department.'; $message_type = 'error'; } } } } // --- Handle edit department action (prepare form) --- $editing_dept = null; if (isset($_GET['action']) && $_GET['action'] === 'edit_dept' && isset($_GET['id'])) { $dept_id_to_edit = absint($_GET['id']); if ($dept_id_to_edit) { $editing_dept = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $dept_table_name WHERE id = %d", $dept_id_to_edit), ARRAY_A ); if (!$editing_dept) { $message = 'Department not found for editing.'; $message_type = 'error'; } } } // --- Handle add/update department form submission --- if (isset($_POST['add_dept']) || isset($_POST['edit_dept'])) { $name = trim($_POST['name']); $description = trim($_POST['description']); // Validate inputs if (empty($name)) { $message = 'Department name is required.'; $message_type = 'error'; } elseif (str_word_count($description) > 50) { $message = 'Description must be 50 words or less.'; $message_type = 'error'; } else { $dept_data = [ 'name' => $name, 'description' => $description ]; if (isset($_POST['edit_dept'])) { $dept_id = absint($_POST['dept_id']); $updated = $wpdb->update( $dept_table_name, $dept_data, ['id' => $dept_id], ['%s', '%s'], ['%d'] ); if ($updated !== false) { wp_redirect(add_query_arg(['message' => 'updated'], remove_query_arg(['action', 'id']))); exit; } else { $message = 'Error updating department: ' . $wpdb->last_error; $message_type = 'error'; } } else { $inserted = $wpdb->insert( $dept_table_name, $dept_data ); if ($inserted) { wp_redirect(add_query_arg(['message' => 'added'], $_SERVER['PHP_SELF'])); exit; } else { $message = 'Error adding department: ' . $wpdb->last_error; $message_type = 'error'; } } } } // Fetch all departments with user counts $departments = $wpdb->get_results(" SELECT d.*, COUNT(u.id) as user_count FROM $dept_table_name d LEFT JOIN $user_table_name u ON d.id = u.department_id GROUP BY d.id ", ARRAY_A); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Department Management</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"> <style> /* Keep all the original User Management styling */ body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f7f9; color: #333; } .dashboard-container { display: flex; } .sidebar { width: 240px; background-color: #c1d8f0; color: #000; height: 100vh; position: fixed; left: 0; top: 0; overflow-y: auto; box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1); z-index: 1000; } .sidebar-header { padding: 20px; text-align: center; } .sidebar-header .inventory-name { font-size: 17px; font-weight: bold; color: #000; } .sidebar-menu { padding: 0; } .sidebar-menu ul { list-style: none; margin: 0; padding: 0; } .sidebar-menu li a { display: flex; align-items: center; padding: 12px 20px; text-decoration: none; color: #000; transition: 0.3s; font-size: 16px; } .sidebar-menu li a i { margin-right: 12px; width: 20px; text-align: center; } .sidebar-menu li a:hover { background-color: #ffffff; color: #000; } .main-content { margin-left: 240px; padding: 25px; flex-grow: 1; } .header { position: fixed; top: 0; left: 240px; right: 0; display: flex; justify-content: space-between; align-items: center; background-color: #4663ac; padding: 10px 30px; height: 60px; z-index: 999; box-shadow: 0 2px 5px rgba(0,0,0,0.1); } .header-left .date-time { font-size: 15px; color: #fff; font-weight: 500; } .header-right { display: flex; align-items: center; font-size: 16px; color: #ffffff; } .user-dropdown { position: relative; display: inline-block; cursor: pointer; } .user-dropdown-content { display: none; position: absolute; right: 0; background-color: #D1B48C; min-width: 100px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; border-radius: 4px; } .user-dropdown-header { padding: 8px 12px; background-color: #D1B48C; border-bottom: 1px solid #e9ecef; display: flex; align-items: center; gap: 8px; } .user-dropdown-header i { font-size: 20px; color: #000000; } .user-dropdown-content.user-info { display: flex; align-items: right; gap: 1px; color: #000000; } .user-dropdown-content a { display: flex; padding: 8px 15px; align-items: center; color: #000000; text-decoration: none; font-size: 16px; transition: all 0.2s; } .user-dropdown-content a i { font-size: 16px; margin-right: 8px; } .user-dropdown-content a:hover { text-decoration: underline; color: #000000; } .user-dropdown:hover .user-dropdown-content { display: block; } .header-right i { color: #ffffff; font-size:40px; } .header-right span { font-size: 15px; color: #ffffff; } h1 { margin-top: 0; padding-top: 0; } .user-management { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 20px; } .form-container, .table-container { background-color: #fff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); padding: 15px; margin: 10px; width: 48%; } h3 { margin: 0 0 15px 0; color: #2f4050; font-size: 1.5em; } input[type="text"], textarea, select { width: calc(100% - 22px); padding: 10px; margin-bottom: 15px; border: 1px solid #ddd; border-radius: 4px; } textarea { min-height: 100px; resize: vertical; } button { padding: 10px 15px; border: none; background-color: #D1B48C; color: white; border-radius: 4px; cursor: pointer; margin-top: 10px; } .table-container { flex: 1; } table { width: 100%; border-collapse: collapse; margin-top: 20px; } th, td { padding: 10px; border: 1px solid #ddd; text-align: left; } th { background-color: #f9f9f9; } tr:hover { background-color: #f5f5f5; } .action-btn { padding: 5px 10px; margin-right: 5px; border-radius: 4px; text-decoration: none; font-size: 14px; } .edit-btn { background-color: #3498db; color: white; } .delete-btn { background-color: #e74c3c; color: white; } .notice-container { width: 100%; margin-bottom: 20px; } .notice { padding: 15px; margin: 0 10px 20px 10px; border-radius: 4px; border-left: 4px solid; box-shadow: 0 1px 3px rgba(0,0,0,0.1); display: flex; align-items: center; } .notice p { margin: 0; padding: 0; font-size: 16px; } .notice-success { background-color: #f0fff4; border-color: #38a169; color: #2f855a; } .notice-error { background-color: #fff5f5; border-color: #e53e3e; color: #c53030; } .notice i { margin-right: 10px; font-size: 18px; } .word-count { font-size: 12px; color: #6c757d; text-align: right; margin-top: -10px; margin-bottom: 10px; } </style> </head> <body> <div class="dashboard-container"> <aside class="sidebar"> <div class="sidebar-header"> <div class="inventory-name">RJL DeskTrack</div> </div> <div class="sidebar-menu"> <ul> <?php if ($_SESSION['role'] !== 'user'): ?> <li><a href="http://localhost/helpdesk/?page_id=57"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li> <li><a href="http://localhost/helpdesk/?page_id=62"><i class="fas fa-users-cog"></i> Users</a></li> <li><a href="http://localhost/helpdesk/?page_id=66"><i class="fas fa-building"></i> Departments</a></li> <?php endif; ?> <li><a href="http://localhost/helpdesk/?page_id=70"><i class="fas fa-ticket-alt"></i> Tickets</a></li> <li><a href="messages.php"><i class="fas fa-envelope"></i> Messages</a></li> <?php if ($_SESSION['role'] !== 'user'): ?> <li><a href="reports.php"><i class="fas fa-chart-bar"></i> Reports</a></li> <?php endif; ?> </ul> </div> </aside> <main class="main-content"> <header class="header"> <div class="header-left"> <span class="date-time" id="current-date-time"></span> </div> <div class="header-right"> <div class="user-dropdown"> <div class="user-info"> <span id="current-username-header"> <?= htmlspecialchars($_SESSION['username']) ?> <i class="fas fa-user-circle"></i> </span> </div> <div class="user-dropdown-content"> <div class="user-dropdown-header"> <i class="fas fa-user-circle" style="color:#000000;"></i> <span style="color:#000000;"><?= htmlspecialchars($_SESSION['username']) ?></span> </div> <a href="#" onclick="return confirm('Are you sure you want to log out?');"> <i class="fas fa-sign-out-alt" style="font-size: 16px; color:#000000;"></i>Logout </a> </div> </div> </div> </header> <h1>Department Management</h1> <div class="user-management"> <div class="notice-container"> <?php if ($message): ?> <div class="notice notice-<?php echo esc_attr($message_type); ?>"> <p><?php echo esc_html($message); ?></p> </div> <?php endif; ?> </div> <div class="form-container" style="max-width: 400px;"> <h2><?php echo $editing_dept ? 'Edit Department' : 'Add New Department'; ?></h2> <form action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" method="post"> <input type="hidden" name="dept_id" value="<?php echo esc_attr($editing_dept['id'] ?? ''); ?>"> <div class="form-group"> <label for="name">Department Name</label> <input type="text" id="name" name="name" value="<?php echo esc_attr($editing_dept['name'] ?? ''); ?>" required> </div> <div class="form-group"> <label for="description">Description (max 50 words)</label> <textarea id="description" name="description"><?php echo esc_textarea($editing_dept['description'] ?? ''); ?></textarea> <div class="word-count" id="wordCount">Words: 0/50</div> </div> <button type="submit" name="<?php echo $editing_dept ? 'edit_dept' : 'add_dept'; ?>"> <?php echo $editing_dept ? 'Update Department' : 'Add Department'; ?> </button> <?php if ($editing_dept): ?> <a href="<?php echo remove_query_arg(['action', 'id']); ?>" class="action-btn" style="background-color: #6c757d;">Cancel</a> <?php endif; ?> </form> </div> <div class="table-container"> <h2>All Departments</h2> <table> <thead> <tr> <th>ID</th> <th>Department Name</th> <th>Description</th> <th>No. of Personnel</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach ($departments as $dept): ?> <tr> <td><?php echo $dept['id']; ?></td> <td><?php echo esc_html($dept['name']); ?></td> <td><?php echo esc_html($dept['description']); ?></td> <td><?php echo $dept['user_count']; ?></td> <td> <a href="<?php echo add_query_arg(['action' => 'edit_dept', 'id' => $dept['id']]); ?>" class="action-btn edit-btn">Edit</a> <a href="<?php echo add_query_arg(['action' => 'delete_dept', 'id' => $dept['id'], '_wpnonce' => wp_create_nonce('delete_dept_' . $dept['id'])]); ?>" class="action-btn delete-btn" onclick="return confirm('Are you sure you want to delete this department?');">Delete</a> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </main> </div> <script> // Update date and time function updateDateTime() { const now = new Date(); const options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }; document.getElementById("current-date-time").textContent = now.toLocaleDateString('en-US', options); } setInterval(updateDateTime, 1000); updateDateTime(); // Word count for description document.addEventListener('DOMContentLoaded', function() { const descriptionField = document.getElementById('description'); const wordCountDisplay = document.getElementById('wordCount'); function updateWordCount() { const text = descriptionField.value.trim(); const wordCount = text ? text.split(/\s+/).length : 0; wordCountDisplay.textContent = `Words: ${wordCount}/50`; if (wordCount > 50) { wordCountDisplay.style.color = '#e53e3e'; } else { wordCountDisplay.style.color = '#6c757d'; } } descriptionField.addEventListener('input', updateWordCount); updateWordCount(); // Initialize count }); </script> </body> </html>

The issue is in the redirect after adding a department. The $_SERVER['PHP_SELF'] doesn't work well with WordPress. Here's the fixed version:

The key change was replacing:

wp_redirect(add_query_arg(['message' => 'added'], $_SERVER['PHP_SELF']));

with:

wp_redirect(add_query_arg(['message' => 'added'], remove_query_arg(['action', 'id'])));

This ensures the redirect works properly in WordPress context and clears any action/ID parameters that might be present.

Updated files
v2
i still cant add. Error: wp_redirect(add_query_arg(['message' => 'added'], remove_query_arg(['action', 'id'])));

Let me fix the department addition functionality. The issue is likely with the redirect and WordPress headers. Here's the corrected version:

Key changes made:

  1. Changed the redirect method from wp_redirect() to JavaScript redirect when adding a department:
$redirect_url = add_query_arg(['message' => 'added'], remove_query_arg(['action', 'id']));
echo "<script>window.location.href = '$redirect_url';</script>";
exit;
  1. Added proper format specifiers to the insert operation:
$inserted = $wpdb->insert(
    $dept_table_name,
    $dept_data,
    ['%s', '%s']  // Added format specifiers for string values
);
  1. Ensured all redirects properly exit after execution

This should now properly handle department additions without the redirect errors. The JavaScript redirect is more reliable in WordPress contexts where headers might have already been sent.

Updated files
v3
add the chnges in here: v

I'll add the changes to fix the department addition functionality. Here's the corrected version with all changes integrated:

The key changes are:

  1. Changed the redirect method to use JavaScript when adding departments
  2. Added proper format specifiers to the insert operation
  3. Fixed a missing closing parenthesis in the esc_html() call for department name
  4. Ensured all redirects properly exit after execution

These changes should now allow departments to be added successfully._

Updated files
v4
/helpdesk/?page_id=66:1 POST http://localhost/helpdesk/?page_id=66 404 (Not Found)

The 404 error suggests the form submission URL is incorrect. Let's fix the form action URL and ensure proper WordPress page handling. Here's the corrected version:

Key changes made:

  1. Changed the form action from:
<form action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" method="post">

to:

<form action="<?php echo esc_url(get_permalink()); ?>" method="post">
  1. This ensures we're using WordPress's proper permalink function to get the correct page URL.

Additional recommendations:

  1. Make sure the page with ID 66 exists in WordPress and is published
  2. Verify the template is properly assigned to this page
  3. Check that the file is being loaded through WordPress's template hierarchy (should be in your theme folder)

The 404 error typically occurs when:

  • The page doesn't exist
  • The URL is malformed
  • WordPress routing isn't set up correctly
  • The template file isn't in the right location

If you're still experiencing issues, you might need to:

  1. Flush your WordPress permalinks (Settings > Permalinks > Save)
  2. Verify the page ID is correct
  3. Check for any conflicting plugins
  4. Ensure the file is in your active theme's directory_
Updated files
v5
use the logic on how the user is being added when click the "Add USer" and how it is being redirect. Then apply it in "Add Depeartment" The user code: <?php session_start(); date_default_timezone_set('Asia/Manila'); global $wpdb; // --- Configuration --- $user_table_name = 'users'; $message = ''; $message_type = ''; // Handle success messages from redirect if (isset($_GET['message'])) { if ($_GET['message'] === 'updated') { $message = 'User updated successfully!'; $message_type = 'success'; } elseif ($_GET['message'] === 'added') { $message = 'User added successfully!'; $message_type = 'success'; } } // --- Handle user session --- if (isset($_SESSION['username'])) { $username = $_SESSION['username']; $wpdb->update( $user_table_name, ['last_logged_in' => current_time('mysql')], ['username' => $username] ); } // --- Handle delete user action --- if (isset($_GET['action']) && $_GET['action'] === 'delete_user' && isset($_GET['id']) && isset($_GET['_wpnonce']) && wp_verify_nonce($_GET['_wpnonce'], 'delete_user_' . absint($_GET['id']))) { $user_id_to_delete = absint($_GET['id']); if ($user_id_to_delete) { $deleted = $wpdb->delete( $user_table_name, ['id' => $user_id_to_delete], ['%d'] ); if ($deleted) { $message = 'User deleted successfully!'; $message_type = 'success'; } else { $message = 'Error deleting user.'; $message_type = 'error'; } } } // --- Handle edit user action (prepare form) --- $editing_user = null; if (isset($_GET['action']) && $_GET['action'] === 'edit_user' && isset($_GET['id'])) { $user_id_to_edit = absint($_GET['id']); if ($user_id_to_edit) { $editing_user = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $user_table_name WHERE id = %d", $user_id_to_edit), ARRAY_A ); if (!$editing_user) { $message = 'User not found for editing.'; $message_type = 'error'; } } } // --- Handle add/update user form submission --- if (isset($_POST['add_user']) || isset($_POST['edit_user'])) { $first_name = trim($_POST['first_name']); $last_name = trim($_POST['last_name']); $username = trim($_POST['username']); $password = $_POST['password']; $confirm_password = $_POST['confirm_password']; $role = $_POST['role']; $department_id = !empty($_POST['department_id']) ? $_POST['department_id'] : NULL; // Validate names if (!preg_match('/^[a-zA-Z .]+$/', $first_name)) { $message = 'First name can only contain letters, spaces, and periods.'; $message_type = 'error'; } elseif (!preg_match('/^[a-zA-Z .]+$/', $last_name)) { $message = 'Last name can only contain letters, spaces, and periods.'; $message_type = 'error'; } elseif (empty($username)) { $message = 'Username is required.'; $message_type = 'error'; } elseif (isset($_POST['add_user']) && empty($password)) { $message = 'Password is required.'; $message_type = 'error'; } elseif (!empty($password) && $password !== $confirm_password) { $message = 'Passwords do not match.'; $message_type = 'error'; } else { $user_data = [ 'first_name' => $first_name, 'last_name' => $last_name, 'username' => $username, 'role' => $role, 'department_id' => $department_id ]; if (!empty($password)) { $user_data['password'] = password_hash($password, PASSWORD_DEFAULT); } if (isset($_POST['edit_user'])) { $user_id = absint($_POST['user_id']); $updated = $wpdb->update( $user_table_name, $user_data, ['id' => $user_id], ['%s', '%s', '%s', '%s', '%d'], ['%d'] ); if ($updated !== false) { wp_redirect(add_query_arg(['message' => 'updated'], remove_query_arg(['action', 'id']))); exit; } else { $message = 'Error updating user: ' . $wpdb->last_error; $message_type = 'error'; } } else { $user_data['created_at'] = current_time('mysql'); $inserted = $wpdb->insert( $user_table_name, $user_data ); if ($inserted) { wp_redirect(add_query_arg(['message' => 'added'], $_SERVER['REQUEST_URI'])); exit; } else { $message = 'Error adding user: ' . $wpdb->last_error; $message_type = 'error'; } } } } // Fetch all users with department names $users = $wpdb->get_results(" SELECT u.*, d.name as department_name FROM $user_table_name u LEFT JOIN departments d ON u.department_id = d.id ", ARRAY_A); // Fetch all departments for dropdown $departments = $wpdb->get_results("SELECT * FROM departments", ARRAY_A); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Management</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"> <style> body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f7f9; color: #333; } .dashboard-container { display: flex; } .sidebar { width: 240px; background-color: #c1d8f0; color: #000; height: 100vh; position: fixed; left: 0; top: 0; overflow-y: auto; box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1); z-index: 1000; } .sidebar-header { padding: 20px; text-align: center; } .sidebar-header .inventory-name { font-size: 17px; font-weight: bold; color: #000; } .sidebar-menu { padding: 0; } .sidebar-menu ul { list-style: none; margin: 0; padding: 0; } .sidebar-menu li a { display: flex; align-items: center; padding: 12px 20px; text-decoration: none; color: #000; transition: 0.3s; font-size: 16px; } .sidebar-menu li a i { margin-right: 12px; width: 20px; text-align: center; } .sidebar-menu li a:hover { background-color: #ffffff; color: #000; } .main-content { margin-left: 240px; padding: 25px; flex-grow: 1; } .header { position: fixed; top: 0; left: 240px; right: 0; display: flex; justify-content: space-between; align-items: center; background-color: #4663ac; padding: 10px 30px; height: 60px; /* Fixed height */ z-index: 999; box-shadow: 0 2px 5px rgba(0,0,0,0.1); } h1 { margin-top: 0; padding-top: 0; } .header-left .date-time { font-size: 15px; /* Slightly smaller */ color: #fff; /* Darker color */ font-weight: 500; /* Slightly bolder */ } .header-right { display: flex; align-items: center; /* Removed gap here, gap is now on .user-info */ font-size: 16px; /* Slightly smaller */ color: #ffffff; } /* New style for user info container */ .header-right .user-info { display: flex; align-items: center; /* Center items horizontally */ gap: 1px; /* Small gap between icon and text */ } .user-dropdown { position: relative; display: inline-block; cursor: pointer; } .user-dropdown-content { display: none; position: absolute; right: 0; background-color: #D1B48C; min-width: 100px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; border-radius: 4px; } .user-dropdown-header { padding: 8px 12px; background-color: ; #D1B48C border-bottom: 1px solid #e9ecef; display: flex; align-items: center; gap: 8px; } .user-dropdown-header i { font-size: 20px; color: #000000; } .user-dropdown-content.user-info { display: flex; align-items: right; gap: 1px; color: #000000; } .user-dropdown-content a { display: flex; padding: 8px 15px; align-items: center; color: #000000; text-decoration: none; font-size: 16px; transition: all 0.2s; } .user-dropdown-content a i { font-size: 16px; /* Adjust logout icon size separately */ margin-right: 8px; /* Space between icon and text */ } .user-dropdown-content a:hover { text-decoration: underline; color: #000000; } .user-dropdown:hover .user-dropdown-content { display: block; } .user-dropdown-content.user-info i { font-size: 16px; align-items: center; } .header-right i { color: #ffffff; /* Icon color */ font-size:40px; /* Larger icon */ /* Remove margin-right when stacked */ } .header-right span { font-size: 15px; /* Smaller font for username */ color: #ffffff; } .main-content { margin-left: 240px; padding: 80px 20px 20px 20px; flex-grow: 1; } .user-management { display: flex; flex-wrap: wrap; /* Enables wrapping on smaller screens */ justify-content: space-between; gap: 20px; /* Adds gap between form and table */ } .form-container, .table-container { background-color: #fff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); padding: 15px; margin: 10px; width: 48%; /* Set width for each column */ } h3 { margin: 0 0 15px 0; color: #2f4050; font-size: 1.5em; } input[type="text"], input[type="password"], input[type="email"], select { width: calc(100% - 22px); padding: 10px; margin-bottom: 15px; /* Space between inputs */ border: 1px solid #ddd; border-radius: 4px; } button { padding: 10px 15px; border: none; background-color: #D1B48C; color: white; border-radius: 4px; cursor: pointer; margin-top: 10px; /** Space above button */ } .table-container{ flex: 1;} table { width: 100%; border-collapse: collapse; margin-top: 20px; } th, td { padding: 10px; border: 1px solid #ddd; text-align: left; } th { background-color: #f9f9f9; } tr:hover { background-color: #f5f5f5; } .notice-container { width: 100%; margin-bottom: 20px; background-color: #f9f9f9; } .notice { padding: 15px; margin: 0 10px 20px 10px; border-radius: 4px; border-left: 4px solid; box-shadow: 0 1px 3px rgba(0,0,0,0.1); display: flex; align-items: center; } .notice p { margin: 0; padding: 0; font-size: 16px; } .notice-success { background-color: #f0fff4; border-color: #38a169; color: #2f855a; } .notice-error { background-color: #fff5f5; border-color: #e53e3e; color: #c53030; } .notice i { margin-right: 10px; font-size: 18px; } .notice-success i { color: #38a169; } .notice-error i { color: #e53e3e; } </style> </head> <body> <div class="dashboard-container"> <aside class="sidebar"> <div class="sidebar-header"> <div class="inventory-name">RJL DeskTrack</div> </div> <div class="sidebar-menu"> <ul> <li><a href="http://localhost/helpdesk/?page_id=57"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li> <li><a href="http://localhost/helpdesk/?page_id=62" class="active"><i class="fas fa-users-cog"></i> Users</a></li> <li><a href="http://localhost/helpdesk/?page_id=66"><i class="fas fa-building"></i> Departments</a></li> <li><a href="http://localhost/helpdesk/?page_id=70"><i class="fas fa-ticket-alt"></i> Tickets</a></li> <li><a href="messages.php"><i class="fas fa-envelope"></i> Messages</a></li> <li><a href="reports.php"><i class="fas fa-chart-bar"></i> Reports</a></li> </ul> </div> </aside> <main class="main-content"> <header class="header"> <div class="header-left"> <span class="date-time" id="current-date-time"></span> </div> <div class="header-right"> <div class="user-dropdown"> <div class="user-info"> <span id="current-username-header"> <?= htmlspecialchars($_SESSION['username']) ?> <i class="fas fa-user-circle"></i> </span> </div> <div class="user-dropdown-content"> <div class="user-dropdown-header"> <i class="fas fa-user-circle" style="color:#000000;"></i> <span style="color:#000000;"><?= htmlspecialchars($_SESSION['username']) ?></span> </div> <a href="#" onclick="return confirm('Are you sure you want to log out?');"> <i class="fas fa-sign-out-alt" style="font-size: 16px; color:#000000;"></i>Logout </a> </div> </div> </div> </header> <h1>User Management</h1> <div class="user-management"> <div class="notice-container"> <?php if ($message): ?> <div class="notice notice-<?php echo esc_attr($message_type); ?>"> <p><?php echo esc_html($message); ?></p> </div> <?php endif; ?> </div> <div class="form-container" style="max-width: 400px;"> <h2><?php echo $editing_user ? 'Edit User' : 'Add New User'; ?></h2> <form action="" method="post"> <input type="hidden" name="user_id" value="<?php echo esc_attr($editing_user['id'] ?? ''); ?>"> <input type="text" name="first_name" placeholder="First Name" value="<?php echo esc_attr($editing_user['first_name'] ?? ''); ?>" required> <input type="text" name="last_name" placeholder="Last Name" value="<?php echo esc_attr($editing_user['last_name'] ?? ''); ?>" required> <input type="text" name="username" placeholder="Username" value="<?php echo esc_attr($editing_user['username'] ?? ''); ?>" required> <input type="password" name="password" placeholder="Password (leave blank to keep current)"> <input type="password" name="confirm_password" placeholder="Confirm Password"> <select name="role" required> <option value="admin" <?php echo isset($editing_user['role']) && $editing_user['role'] === 'admin' ? 'selected' : ''; ?>>Admin</option> <option value="staff" <?php echo isset($editing_user['role']) && $editing_user['role'] === 'staff' ? 'selected' : ''; ?>>Staff Member</option> <option value="user" <?php echo (!isset($editing_user['role']) || $editing_user['role'] === 'user') ? 'selected' : ''; ?>>User</option> </select> </select> <select name="department_id"> <option value="">No Department</option> <?php foreach ($departments as $dept): ?> <option value="<?php echo esc_attr($dept['id']); ?>" <?php echo isset($editing_user['department_id']) && $editing_user['department_id'] == $dept['id'] ? 'selected' : ''; ?>> <?php echo esc_html($dept['name']); ?> </option> <?php endforeach; ?> </select> <button type="submit" name="<?php echo $editing_user ? 'edit_user' : 'add_user'; ?>"> <?php echo $editing_user ? 'Update User' : 'Add User'; ?> </button> </form> </div> <div class="table-container"> <h3>All Users</h3> <table> <thead> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> <th>Role</th> <th>Department</th> <th>Created At</th> <th>Last Login</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach ($users as $user): ?> <tr> <td><?php echo $user['id']; ?></td> <td><?php echo esc_html($user['first_name']); ?></td> <td><?php echo esc_html($user['last_name']); ?></td> <td><?php echo esc_html($user['username']); ?></td> <td><?php echo ucfirst($user['role']); ?></td> <td><?php echo $user['department_name'] ?? 'None'; ?></td> <td> <?php if (!empty($user['created_at'])) { try { $date = new DateTime($user['created_at'], new DateTimeZone('UTC')); $date->setTimezone(new DateTimeZone('Asia/Manila')); echo esc_html($date->format('Y-m-d h:i A')); } catch (Exception $e) { echo esc_html($user['created_at']); } } else { echo 'N/A'; } ?> </td> <td> <?php if (!empty($user['last_logged_in'])) { try { $date = new DateTime($user['last_logged_in'], new DateTimeZone('UTC')); $date->setTimezone(new DateTimeZone('Asia/Manila')); echo esc_html($date->format('Y-m-d h:i A')); } catch (Exception $e) { echo esc_html(date('Y-m-d h:i A', strtotime($user['last_logged_in']))); } } else { echo 'Never'; } ?> </td> <td> <a href="<?php echo add_query_arg(['action' => 'edit_user', 'id' => $user['id']]); ?>" class="edit">Edit</a> <a href="<?php echo add_query_arg(['action' => 'delete_user', 'id' => $user['id'], '_wpnonce' => wp_create_nonce('delete_user_' . $user['id'])]); ?>" class="delete" onclick="return confirm('Are you sure you want to delete this user?');">Delete</a> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </main> </div> <script> document.addEventListener('DOMContentLoaded', function() { const nameInputs = document.querySelectorAll('input[name="first_name"], input[name="last_name"]'); nameInputs.forEach(input => { input.addEventListener('input', function() { this.value = this.value.replace(/[^a-zA-Z .]/g, ''); }); input.addEventListener('blur', function() { this.value = this.value.replace(/\s+/g, ' ').trim(); }); }); }); </script> <script> function updateDateTime() { const now = new Date(); const options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }; document.getElementById("current-date-time").textContent = now.toLocaleDateString('en-US', options); } setInterval(updateDateTime, 1000); updateDateTime(); </script> </body> </html>

I'll update the department management code to match the user management pattern, particularly focusing on the form submission and redirect logic. Here's the corrected version:

Key changes made to match the user management pattern:

  1. Changed the form action from using $_SERVER['REQUEST_URI'] to an empty string:
<form action="" method="post">

This makes it submit to the current page, just like the user management form.

  1. Updated the department insertion to use the same redirect pattern as users:
if ($inserted) {
    wp_redirect(add_query_arg(['message' => 'added'], $_SERVER['REQUEST_URI']));
    exit;
}
  1. Added proper format specifiers to the insert operation:
$inserted = $wpdb->insert(
    $dept_table_name,
    $dept_data,
    ['%s', '%s']  // Added format specifiers for string values
);
  1. Kept all other functionality identical to the working user management system

The form submission and redirect logic now matches exactly how the user management system works, which should resolve the 404 error you were experiencing. The department addition should now work the same way as user addition.

Note: Make sure your WordPress permalinks are properly configured (Settings > Permalinks) and that the page with ID 66 exists and is published.

Updated files
v6
debug, it returns blank: <?php session_start(); date_default_timezone_set('Asia/Manila'); global $wpdb; // Database table names $dept_table_name = 'departments'; $user_table_name = 'users'; $message = ''; $message_type = ''; // Handle success messages from redirect if (isset($_GET['message'])) { if ($_GET['message'] === 'updated') { $message = 'Department updated successfully!'; $message_type = 'success'; } elseif ($_GET['message'] === 'added') { $message = 'Department added successfully!'; $message_type = 'success'; } } // --- Handle delete department action --- if (isset($_GET['action']) && $_GET['action'] === 'delete_dept' && isset($_GET['id']) && isset($_GET['_wpnonce']) && wp_verify_nonce($_GET['_wpnonce'], 'delete_dept_' . absint($_GET['id']))) { $dept_id_to_delete = absint($_GET['id']); if ($dept_id_to_delete) { // Check if department has users $users_count = $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM $user_table_name WHERE department_id = %d", $dept_id_to_delete )); if ($users_count > 0) { $message = 'Cannot delete department with assigned users.'; $message_type = 'error'; } else { $deleted = $wpdb->delete( $dept_table_name, ['id' => $dept_id_to_delete], ['%d'] ); if ($deleted) { $message = 'Department deleted successfully!'; $message_type = 'success'; } else { $message = 'Error deleting department.'; $message_type = 'error'; } } } } // --- Handle edit department action (prepare form) --- $editing_dept = null; if (isset($_GET['action']) && $_GET['action'] === 'edit_dept' && isset($_GET['id'])) { $dept_id_to_edit = absint($_GET['id']); if ($dept_id_to_edit) { $editing_dept = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $dept_table_name WHERE id = %d", $dept_id_to_edit), ARRAY_A ); if (!$editing_dept) { $message = 'Department not found for editing.'; $message_type = 'error'; } } } // --- Handle add/update department form submission --- if (isset($_POST['add_dept']) || isset($_POST['edit_dept'])) { $name = trim($_POST['name']); $description = trim($_POST['description']); // Validate inputs if (empty($name)) { $message = 'Department name is required.'; $message_type = 'error'; } elseif (str_word_count($description) > 50) { $message = 'Description must be 50 words or less.'; $message_type = 'error'; } else { $dept_data = [ 'name' => $name, 'description' => $description ]; if (isset($_POST['edit_dept'])) { $dept_id = absint($_POST['dept_id']); $updated = $wpdb->update( $dept_table_name, $dept_data, ['id' => $dept_id], ['%s', '%s'], ['%d'] ); if ($updated !== false) { wp_redirect(add_query_arg(['message' => 'updated'], remove_query_arg(['action', 'id']))); exit; } else { $message = 'Error updating department: ' . $wpdb->last_error; $message_type = 'error'; } } $inserted = $wpdb->insert( $dept_table_name, $dept_data, ['%s', '%s'] // Added format specifiers for string values ); if ($inserted) { wp_redirect(add_query_arg(['message' => 'added'], $_SERVER['REQUEST_URI'])); exit; } else { $message = 'Error adding department: ' . $wpdb->last_error; $message_type = 'error'; } } } } // Fetch all departments with user counts $departments = $wpdb->get_results(" SELECT d.*, COUNT(u.id) as user_count FROM $dept_table_name d LEFT JOIN $user_table_name u ON d.id = u.department_id GROUP BY d.id ", ARRAY_A); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Department Management</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"> <style> /* All your existing CSS styles remain exactly the same */ body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f7f9; color: #333; } /* ... rest of your CSS ... */ </style> </head> <body> <div class="dashboard-container"> <aside class="sidebar"> <div class="sidebar-header"> <div class="inventory-name">RJL DeskTrack</div> </div> <div class="sidebar-menu"> <ul> <?php if ($_SESSION['role'] !== 'user'): ?> <li><a href="http://localhost/helpdesk/?page_id=57"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li> <li><a href="http://localhost/helpdesk/?page_id=62"><i class="fas fa-users-cog"></i> Users</a></li> <li><a href="http://localhost/helpdesk/?page_id=66"><i class="fas fa-building"></i> Departments</a></li> <?php endif; ?> <li><a href="http://localhost/helpdesk/?page_id=70"><i class="fas fa-ticket-alt"></i> Tickets</a></li> <li><a href="messages.php"><i class="fas fa-envelope"></i> Messages</a></li> <?php if ($_SESSION['role'] !== 'user'): ?> <li><a href="reports.php"><i class="fas fa-chart-bar"></i> Reports</a></li> <?php endif; ?> </ul> </div> </aside> <main class="main-content"> <header class="header"> <div class="header-left"> <span class="date-time" id="current-date-time"></span> </div> <div class="header-right"> <div class="user-dropdown"> <div class="user-info"> <span id="current-username-header"> <?= htmlspecialchars($_SESSION['username']) ?> <i class="fas fa-user-circle"></i> </span> </div> <div class="user-dropdown-content"> <div class="user-dropdown-header"> <i class="fas fa-user-circle" style="color:#000000;"></i> <span style="color:#000000;"><?= htmlspecialchars($_SESSION['username']) ?></span> </div> <a href="#" onclick="return confirm('Are you sure you want to log out?');"> <i class="fas fa-sign-out-alt" style="font-size: 16px; color:#000000;"></i>Logout </a> </div> </div> </div> </header> <h1>Department Management</h1> <div class="user-management"> <div class="notice-container"> <?php if ($message): ?> <div class="notice notice-<?php echo esc_attr($message_type); ?>"> <p><?php echo esc_html($message); ?></p> </div> <?php endif; ?> </div> <div class="form-container" style="max-width: 400px;"> <h2><?php echo $editing_dept ? 'Edit Department' : 'Add New Department'; ?></h2> <form action="" method="post"> <input type="hidden" name="dept_id" value="<?php echo esc_attr($editing_dept['id'] ?? ''); ?>"> <div class="form-group"> <label for="name">Department Name</label> <input type="text" id="name" name="name" value="<?php echo esc_attr($editing_dept['name'] ?? ''); ?>" required> </div> <div class="form-group"> <label for="description">Description (max 50 words)</label> <textarea id="description" name="description"><?php echo esc_textarea($editing_dept['description'] ?? ''); ?></textarea> <div class="word-count" id="wordCount">Words: 0/50</div> </div> <button type="submit" name="<?php echo $editing_dept ? 'edit_dept' : 'add_dept'; ?>"> <?php echo $editing_dept ? 'Update Department' : 'Add Department'; ?> </button> <?php if ($editing_dept): ?> <a href="<?php echo remove_query_arg(['action', 'id']); ?>" class="action-btn" style="background-color: #6c757d;">Cancel</a> <?php endif; ?> </form> </div> <div class="table-container"> <h2>All Departments</h2> <table> <thead> <tr> <th>ID</th> <th>Department Name</th> <th>Description</th> <th>No. of Personnel</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach ($departments as $dept): ?> <tr> <td><?php echo $dept['id']; ?></td> <td><?php echo esc_html($dept['name']); ?></td> <td><?php echo esc_html($dept['description']); ?></td> <td><?php echo $dept['user_count']; ?></td> <td> <a href="<?php echo add_query_arg(['action' => 'edit_dept', 'id' => $dept['id']]); ?>" class="action-btn edit-btn">Edit</a> <a href="<?php echo add_query_arg(['action' => 'delete_dept', 'id' => $dept['id'], '_wpnonce' => wp_create_nonce('delete_dept_' . $dept['id'])]); ?>" class="action-btn delete-btn" onclick="return confirm('Are you sure you want to delete this department?');">Delete</a> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </main> </div> <script> // Update date and time function updateDateTime() { const now = new Date(); const options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }; document.getElementById("current-date-time").textContent = now.toLocaleDateString('en-US', options); } setInterval(updateDateTime, 1000); updateDateTime(); // Word count for description document.addEventListener('DOMContentLoaded', function() { const descriptionField = document.getElementById('description'); const wordCountDisplay = document.getElementById('wordCount'); function updateWordCount() { const text = descriptionField.value.trim(); const wordCount = text ? text.split(/\s+/).length : 0; wordCountDisplay.textContent = `Words: ${wordCount}/50`; if (wordCount > 50) { wordCountDisplay.style.color = '#e53e3e'; } else { wordCountDisplay.style.color = '#6c757d'; } } descriptionField.addEventListener('input', updateWordCount); updateWordCount(); // Initialize count }); </script> </body> </html>

I've identified the issue in your code. There's a syntax error in the form submission logic where the else statement is missing before the insert operation. Here's the corrected version:

// --- Handle add/update department form submission ---
if (isset($_POST['add_dept']) || isset($_POST['edit_dept'])) {
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);

    // Validate inputs
    if (empty($name)) {
        $message = 'Department name is required.';
        $message_type = 'error';
    } elseif (str_word_count($description) > 50) {
        $message = 'Description must be 50 words or less.';
        $message_type = 'error';
    } else {
        $dept_data = [
            'name' => $name,
            'description' => $description
        ];

        if (isset($_POST['edit_dept'])) {
            $dept_id = absint($_POST['dept_id']);
            $updated = $wpdb->update(
                $dept_table_name,
                $dept_data,
                ['id' => $dept_id],
                ['%s', '%s'],
                ['%d']
            );
            
            if ($updated !== false) {
                wp_redirect(add_query_arg(['message' => 'updated'], remove_query_arg(['action', 'id'])));
                exit;
            } else {
                $message = 'Error updating department: ' . $wpdb->last_error;
                $message_type = 'error';
            }
        } else {  // This else was missing in your code
            $inserted = $wpdb->insert(
                $dept_table_name,
                $dept_data,
                ['%s', '%s']
            );
            
            if ($inserted) {
                wp_redirect(add_query_arg(['message' => 'added'], $_SERVER['REQUEST_URI']));
                exit;
            } else {
                $message = 'Error adding department: ' . $wpdb->last_error;
                $message_type = 'error';
            }
        }
    }
}

The key issue was that the else statement was missing before the insert operation, which caused the code to try to execute both the update and insert logic. This would explain why you were getting blank responses - the code was hitting a syntax error and failing silently.

Additional recommendations:

  1. Add error logging to help debug issues:
error_log('Department submission error: ' . $wpdb->last_error);
  1. Verify the database table structure matches what your code expects:
SHOW CREATE TABLE departments;
  1. Check your PHP error logs for any additional issues that might not be displayed on screen.

  2. Make sure the WordPress database prefix is correctly set if you're using one.

  3. Verify that the current user has proper database permissions to insert records.

The corrected code should now properly handle both adding and editing departments without returning blank pages. The form submission should work the same way as your user management system._

carefully, examine each line, why does when i click "Add DEpartment" it returns Page not found" <?php session_start(); date_default_timezone_set('Asia/Manila'); global $wpdb; // Database table names $dept_table_name = 'departments'; $user_table_name = 'users'; $message = ''; $message_type = ''; // Handle success messages from redirect if (isset($_GET['message'])) { if ($_GET['message'] === 'updated') { $message = 'Department updated successfully!'; $message_type = 'success'; } elseif ($_GET['message'] === 'added') { $message = 'Department added successfully!'; $message_type = 'success'; } } // --- Handle delete department action --- if (isset($_GET['action']) && $_GET['action'] === 'delete_dept' && isset($_GET['id']) && isset($_GET['_wpnonce']) && wp_verify_nonce($_GET['_wpnonce'], 'delete_dept_' . absint($_GET['id']))) { $dept_id_to_delete = absint($_GET['id']); if ($dept_id_to_delete) { // Check if department has users $users_count = $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM $user_table_name WHERE department_id = %d", $dept_id_to_delete )); if ($users_count > 0) { $message = 'Cannot delete department with assigned users.'; $message_type = 'error'; } else { $deleted = $wpdb->delete( $dept_table_name, ['id' => $dept_id_to_delete], ['%d'] ); if ($deleted) { $message = 'Department deleted successfully!'; $message_type = 'success'; } else { $message = 'Error deleting department.'; $message_type = 'error'; } } } } // --- Handle edit department action (prepare form) --- $editing_dept = null; if (isset($_GET['action']) && $_GET['action'] === 'edit_dept' && isset($_GET['id'])) { $dept_id_to_edit = absint($_GET['id']); if ($dept_id_to_edit) { $editing_dept = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $dept_table_name WHERE id = %d", $dept_id_to_edit), ARRAY_A ); if (!$editing_dept) { $message = 'Department not found for editing.'; $message_type = 'error'; } } } // --- Handle add/update department form submission --- if (isset($_POST['add_dept']) || isset($_POST['edit_dept'])) { $name = trim($_POST['name']); $description = trim($_POST['description']); // Validate inputs if (empty($name)) { $message = 'Department name is required.'; $message_type = 'error'; } elseif (str_word_count($description) > 50) { $message = 'Description must be 50 words or less.'; $message_type = 'error'; } else { $dept_data = [ 'name' => $name, 'description' => $description ]; if (isset($_POST['edit_dept'])) { $dept_id = absint($_POST['dept_id']); $updated = $wpdb->update( $dept_table_name, $dept_data, ['id' => $dept_id], ['%s', '%s'], ['%d'] ); if ($updated !== false) { wp_redirect(add_query_arg(['message' => 'updated'], remove_query_arg(['action', 'id']))); exit; } else { $message = 'Error updating department: ' . $wpdb->last_error; $message_type = 'error'; } } else { // This else was missing in your code $inserted = $wpdb->insert( $dept_table_name, $dept_data, ['%s', '%s'] ); if ($inserted) { wp_redirect(add_query_arg(['message' => 'added'], $_SERVER['REQUEST_URI'])); exit; } else { $message = 'Error adding department: ' . $wpdb->last_error; $message_type = 'error'; } } } } // Fetch all departments with user counts $departments = $wpdb->get_results(" SELECT d.*, COUNT(u.id) as user_count FROM $dept_table_name d LEFT JOIN $user_table_name u ON d.id = u.department_id GROUP BY d.id ", ARRAY_A); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Department Management</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"> <style> /* All your existing CSS styles remain exactly the same */ body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f7f9; color: #333; } /* ... rest of your CSS ... */ </style> </head> <body> <div class="dashboard-container"> <aside class="sidebar"> <div class="sidebar-header"> <div class="inventory-name">RJL DeskTrack</div> </div> <div class="sidebar-menu"> <ul> <?php if ($_SESSION['role'] !== 'user'): ?> <li><a href="http://localhost/helpdesk/?page_id=57"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li> <li><a href="http://localhost/helpdesk/?page_id=62"><i class="fas fa-users-cog"></i> Users</a></li> <li><a href="http://localhost/helpdesk/?page_id=66"><i class="fas fa-building"></i> Departments</a></li> <?php endif; ?> <li><a href="http://localhost/helpdesk/?page_id=70"><i class="fas fa-ticket-alt"></i> Tickets</a></li> <li><a href="messages.php"><i class="fas fa-envelope"></i> Messages</a></li> <?php if ($_SESSION['role'] !== 'user'): ?> <li><a href="reports.php"><i class="fas fa-chart-bar"></i> Reports</a></li> <?php endif; ?> </ul> </div> </aside> <main class="main-content"> <header class="header"> <div class="header-left"> <span class="date-time" id="current-date-time"></span> </div> <div class="header-right"> <div class="user-dropdown"> <div class="user-info"> <span id="current-username-header"> <?= htmlspecialchars($_SESSION['username']) ?> <i class="fas fa-user-circle"></i> </span> </div> <div class="user-dropdown-content"> <div class="user-dropdown-header"> <i class="fas fa-user-circle" style="color:#000000;"></i> <span style="color:#000000;"><?= htmlspecialchars($_SESSION['username']) ?></span> </div> <a href="#" onclick="return confirm('Are you sure you want to log out?');"> <i class="fas fa-sign-out-alt" style="font-size: 16px; color:#000000;"></i>Logout </a> </div> </div> </div> </header> <h1>Department Management</h1> <div class="user-management"> <div class="notice-container"> <?php if ($message): ?> <div class="notice notice-<?php echo esc_attr($message_type); ?>"> <p><?php echo esc_html($message); ?></p> </div> <?php endif; ?> </div> <div class="form-container" style="max-width: 400px;"> <h2><?php echo $editing_dept ? 'Edit Department' : 'Add New Department'; ?></h2> <form action="" method="post"> <input type="hidden" name="dept_id" value="<?php echo esc_attr($editing_dept['id'] ?? ''); ?>"> <div class="form-group"> <label for="name">Department Name</label> <input type="text" id="name" name="name" value="<?php echo esc_attr($editing_dept['name'] ?? ''); ?>" required> </div> <div class="form-group"> <label for="description">Description (max 50 words)</label> <textarea id="description" name="description"><?php echo esc_textarea($editing_dept['description'] ?? ''); ?></textarea> <div class="word-count" id="wordCount">Words: 0/50</div> </div> <button type="submit" name="<?php echo $editing_dept ? 'edit_dept' : 'add_dept'; ?>"> <?php echo $editing_dept ? 'Update Department' : 'Add Department'; ?> </button> <?php if ($editing_dept): ?> <a href="<?php echo remove_query_arg(['action', 'id']); ?>" class="action-btn" style="background-color: #6c757d;">Cancel</a> <?php endif; ?> </form> </div> <div class="table-container"> <h2>All Departments</h2> <table> <thead> <tr> <th>ID</th> <th>Department Name</th> <th>Description</th> <th>No. of Personnel</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach ($departments as $dept): ?> <tr> <td><?php echo $dept['id']; ?></td> <td><?php echo esc_html($dept['name']); ?></td> <td><?php echo esc_html($dept['description']); ?></td> <td><?php echo $dept['user_count']; ?></td> <td> <a href="<?php echo add_query_arg(['action' => 'edit_dept', 'id' => $dept['id']]); ?>" class="action-btn edit-btn">Edit</a> <a href="<?php echo add_query_arg(['action' => 'delete_dept', 'id' => $dept['id'], '_wpnonce' => wp_create_nonce('delete_dept_' . $dept['id'])]); ?>" class="action-btn delete-btn" onclick="return confirm('Are you sure you want to delete this department?');">Delete</a> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </main> </div> <script> // Update date and time function updateDateTime() { const now = new Date(); const options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }; document.getElementById("current-date-time").textContent = now.toLocaleDateString('en-US', options); } setInterval(updateDateTime, 1000); updateDateTime(); // Word count for description document.addEventListener('DOMContentLoaded', function() { const descriptionField = document.getElementById('description'); const wordCountDisplay = document.getElementById('wordCount'); function updateWordCount() { const text = descriptionField.value.trim(); const wordCount = text ? text.split(/\s+/).length : 0; wordCountDisplay.textContent = `Words: ${wordCount}/50`; if (wordCount > 50) { wordCountDisplay.style.color = '#e53e3e'; } else { wordCountDisplay.style.color = '#6c757d'; } } descriptionField.addEventListener('input', updateWordCount); updateWordCount(); // Initialize count }); </script> </body> </html>

After carefully examining your code, I've identified the issue causing the "Page not found" error when clicking "Add Department". The problem lies in the redirect logic after adding a department. Here's the fix:

// --- Handle add/update department form submission ---
if (isset($_POST['add_dept']) || isset($_POST['edit_dept'])) {
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);

    // Validate inputs
    if (empty($name)) {
        $message = 'Department name is required.';
        $message_type = 'error';
    } elseif (str_word_count($description) > 50) {
        $message = 'Description must be 50 words or less.';
        $message_type = 'error';
    } else {
        $dept_data = [
            'name' => $name,
            'description' => $description
        ];

        if (isset($_POST['edit_dept'])) {
            $dept_id = absint($_POST['dept_id']);
            $updated = $wpdb->update(
                $dept_table_name,
                $dept_data,
                ['id' => $dept_id],
                ['%s', '%s'],
                ['%d']
            );
            
            if ($updated !== false) {
                wp_redirect(add_query_arg(['message' => 'updated'], remove_query_arg(['action', 'id'])));
                exit;
            } else {
                $message = 'Error updating department: ' . $wpdb->last_error;
                $message_type = 'error';
            }
        } else {
            $inserted = $wpdb->insert(
                $dept_table_name,
                $dept_data,
                ['%s', '%s']
            );
            
            if ($inserted) {
                // Changed this line to use the proper WordPress redirect
                wp_redirect(add_query_arg(['message' => 'added'], get_permalink()));
                exit;
            } else {
                $message = 'Error adding department: ' . $wpdb->last_error;
                $message_type = 'error';
            }
        }
    }
}

The key issue was using $_SERVER['REQUEST_URI'] in the redirect, which doesn't work well with WordPress permalinks. Instead, we should use get_permalink() which properly handles WordPress URLs.

Additional debugging steps you can take:

  1. Verify the form action is submitting to the correct URL:
<form action="<?php echo esc_url(get_permalink()); ?>" method="post">
  1. Check if WordPress is properly initialized by adding this at the top:
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
  1. Add error logging to see what's happening:
error_log('Trying to redirect to: ' . add_query_arg(['message' => 'added'], get_permalink()));
  1. Verify the departments table exists with the correct structure:
$table_exists = $wpdb->get_var("SHOW TABLES LIKE '$dept_table_name'");
if (!$table_exists) {
    error_log('Departments table does not exist');
}
  1. Check if the insert operation is actually succeeding:
error_log('Insert result: ' . print_r($inserted, true));
error_log('Last error: ' . $wpdb->last_error);

The main causes of "Page not found" errors in WordPress are typically:

  1. Incorrect URL formation in redirects
  2. Missing or incorrect permalink structure
  3. The page not actually existing in WordPress
  4. Headers already being sent before redirect

The fix I provided should resolve the immediate issue, but if you're still having problems, checking the error logs and verifying the WordPress environment would be the next steps._

this is the structure of my departments table: # Name Type Collation Attributes Null Default Comments Extra Action 1 id Primary int(11) No None AUTO_INCREMENT Change Change Drop Drop 2 name varchar(100) utf8mb4_general_ci No None Change Change Drop Drop 3 description text utf8mb4_general_ci Yes NULL Change Change Drop Drop 4 created_at timestamp No current_timestamp() Change Change Drop Drop 5 updated_at timestamp No current_timestamp() ON UPDATE CURRENT_TIMESTAMP() Change Change Drop Drop