prepare('SELECT id, name, email, role_id FROM users WHERE id = ?'); $stmt->execute([$user_id]); $user = $stmt->fetch(); if (!$user) { header('Location: users.php'); exit; } // Fetch all roles for the dropdown $roles_stmt = $pdo->query('SELECT id, name FROM roles ORDER BY name'); $roles = $roles_stmt->fetchAll(); } catch (PDOException $e) { $error_message = 'Database error: ' . $e->getMessage(); } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $data = []; $set_parts = []; foreach ($allowed_fields as $field) { if (isset($_POST[$field])) { $data[] = $_POST[$field]; $set_parts[] = "$field = ?"; } } $data[] = $user_id; if (empty($set_parts)) { $error_message = 'No data submitted.'; } else { try { $pdo = db(); // Check if email already exists for another user if (in_array('email', $allowed_fields)) { $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ? AND id != ?'); $stmt->execute([$_POST['email'], $user_id]); if ($stmt->fetch()) { $error_message = 'A user with this email address already exists.'; } } if (!$error_message) { $sql = sprintf("UPDATE users SET %s WHERE id = ?", implode(', ', $set_parts)); $stmt = $pdo->prepare($sql); $stmt->execute($data); header("Location: users.php?success=user_updated"); exit; } } catch (PDOException $e) { $error_message = 'Database error: ' . $e->getMessage(); } } } ?> Edit User - IC-Inventory

Edit User

Cancel