89 lines
3.3 KiB
PHP
89 lines
3.3 KiB
PHP
<?php
|
|
session_start();
|
|
|
|
if (!isset($_SESSION['user_id'])) {
|
|
header('Location: login.php');
|
|
exit;
|
|
}
|
|
|
|
require_once 'db/config.php';
|
|
|
|
$user_id = $_SESSION['user_id'];
|
|
$message = '';
|
|
$error = '';
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$username = trim($_POST['username']);
|
|
$email = trim($_POST['email']);
|
|
|
|
if (empty($username) || empty($email)) {
|
|
$error = 'Username and email are required.';
|
|
} else {
|
|
// Check for duplicate username
|
|
$stmt = db()->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
|
|
$stmt->execute([$username, $user_id]);
|
|
if ($stmt->fetch()) {
|
|
$error = 'Username already taken.';
|
|
} else {
|
|
// Check for duplicate email
|
|
$stmt = db()->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
|
|
$stmt->execute([$email, $user_id]);
|
|
if ($stmt->fetch()) {
|
|
$error = 'Email already in use.';
|
|
} else {
|
|
// Update user
|
|
$stmt = db()->prepare("UPDATE users SET username = ?, email = ? WHERE id = ?");
|
|
if ($stmt->execute([$username, $email, $user_id])) {
|
|
$message = 'Profile updated successfully!';
|
|
} else {
|
|
$error = 'Failed to update profile.';
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
$stmt = db()->prepare("SELECT username, email FROM users WHERE id = ?");
|
|
$stmt->execute([$user_id]);
|
|
$user = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
|
|
require_once 'includes/header.php';
|
|
?>
|
|
|
|
<div class="container mt-5">
|
|
<div class="row justify-content-center">
|
|
<div class="col-md-6">
|
|
<div class="card">
|
|
<div class="card-header">
|
|
<h2>User Profile</h2>
|
|
</div>
|
|
<div class="card-body">
|
|
<?php if ($message): ?>
|
|
<div class="alert alert-success"><?php echo $message; ?></div>
|
|
<?php endif; ?>
|
|
<?php if ($error): ?>
|
|
<div class="alert alert-danger"><?php echo $error; ?></div>
|
|
<?php endif; ?>
|
|
|
|
<?php if ($user): ?>
|
|
<form method="POST" action="profile.php">
|
|
<div class="mb-3">
|
|
<label for="username" class="form-label">Username</label>
|
|
<input type="text" class="form-control" id="username" name="username" value="<?php echo htmlspecialchars($user['username']); ?>" required>
|
|
</div>
|
|
<div class="mb-3">
|
|
<label for="email" class="form-label">Email</label>
|
|
<input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
|
|
</div>
|
|
<button type="submit" class="btn btn-primary">Update Profile</button>
|
|
</form>
|
|
<?php else: ?>
|
|
<p class="text-danger">Could not retrieve user information.</p>
|
|
<?php endif; ?>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<?php require_once 'includes/footer.php'; ?>
|