So, I've got a register form that I want all the usernames (email adresses) have to be unique, I made it so the database entries have to be unique, but then the error that the user gets is my generic one (see $message), which I could change to another message, but then the user wouldn't know whether the account hasn't been created due to an error server side or a duplicate email address.
$message = 'Sorry there must have been an issue creating your account';
What I have been struggling to get is a way to have a custom error that says something like: "Sorry this email is already in use" when the username is already in use.
Below is the code for my register form (i didnt make this)):
<?php
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: restricted.php");
}
require 'database.php';
$message = '';
if(!empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['firstname']) && !empty($_POST['surname'])):
// Enter the new user in the database
$sql = "INSERT INTO users (email, password, firstname, surname) VALUES (:email, :password, :firstname, :surname)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
$stmt->bindParam(':firstname', $_POST['firstname']);
$stmt->bindParam(':surname', $_POST['surname']);
if( $stmt->execute() ):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
endif;
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<?php include '../header.php'; ?>
</head>
<body>
<?php if(!empty($message)): ?>
<p><?= $message ?></p>
<?php endif; ?>
<h1>Register</h1>
<span>or <a href="login.php">login here</a></span>
<form action="register.php" method="POST">
<input type="text" placeholder="Enter your email" name="email">
<input type="password" placeholder="and password" name="password">
<input type="password" placeholder="confirm password" name="confirm_password">
<input type="text" placeholder="Enter your first name" name="firstname">
<input type="text" placeholder="Enter your surname" name="surname">
<input type="submit">
</form>
</body>
</html>