Reputation: 47
I've created a user login system and have a page where users can update their details. The email address and username need to be unique so I added validation to the update form. However, when the form is submitted it errors saying the email address is already in use. Can I exclude the current email (stored in the session) from the duplicate check somehow?
This is my code, but not all as it's a bit long, I also need to do the same validation check for the username:
try {
$stmt = $db->prepare('SELECT email, username, firstname, middlename, lastname FROM members WHERE memberID = :memberID');
$stmt->execute(array(':memberID' => $_SESSION['memberID']));
$row = $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
//process form
if(isset($_POST['submit'])){
// email validation
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$error[] = 'Please enter a valid email address';
} else {
$stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
$stmt->execute(array(':email' => $_POST['email']));
$emailcheck = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($emailcheck['email'])){
$error[] = 'Email provided is already in use.';
}
}
// insert to DB
if(!isset($error)){
try {
$stmt = $db->prepare('UPDATE members SET username=:username, firstname=:firstname, middlename=:middlename, lastname=:lastname, email=:email, updated=NOW() WHERE memberID = :memberID');
$stmt->execute(array(
':username' => $_POST['username'],
':firstname' => $_POST['firstname'],
':middlename' => $_POST['middlename'],
':lastname' => $_POST['lastname'],
':email' => $_POST['email'],
':memberID' => $_SESSION['memberID']
));
//redirect to page with updated message
header('Location: personal-details.php?action=updated');
exit;
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
} else {
$error[] = 'Update error';
}
}
Then in each text box I used:
<input type="text" name="username" id="username" class="form-control" value="<?php echo($row['username']) ?>" tabindex="1">
Upvotes: 2
Views: 432
Reputation: 91742
You can use the memberID
like you do in the other queries as well, but excluding it:
SELECT email FROM members WHERE email = :email AND memberID != :memberID
Upvotes: 5