prepare("SELECT id FROM users WHERE email = ? AND id != ?"); $stmt->execute([$email, $id]); if ($stmt->fetch()) { $errors['email'] = 'Email already exists.'; } } catch (PDOException $e) { $errors['db'] = "Database error: " . $e->getMessage(); } } if (!empty($password) && strlen($password) < 8) { $errors['password'] = 'Password must be at least 8 characters long.'; } if (empty($errors)) { try { $pdo = db(); if ($password) { $hashed_password = password_hash($password, PASSWORD_DEFAULT); $sql = "UPDATE users SET name = ?, email = ?, password = ?, role = ? WHERE id = ?"; $stmt = $pdo->prepare($sql); $stmt->execute([$name, $email, $hashed_password, $role, $id]); } else { $sql = "UPDATE users SET name = ?, email = ?, role = ? WHERE id = ?"; $stmt = $pdo->prepare($sql); $stmt->execute([$name, $email, $role, $id]); } $_SESSION['success_message'] = 'User updated successfully.'; header("Location: users.php"); exit; } catch (PDOException $e) { $errors['db'] = "Database error: " . $e->getMessage(); } } $_SESSION['errors'] = $errors; $_SESSION['old_input'] = $_POST; header("Location: edit_user.php?id=" . $id); exit; } header("Location: users.php"); exit;