Reputation: 111
Is it possible to split the Username or Email already exists
into specific error messages?
I'm working on this user registration script, if you have any tips about the rest of code given would be much appreciated
if(isset($_POST['register'])){
if(
// check if posts not empty
empty($_POST['username']) ||
empty($_POST['email']) ||
empty($_POST['password']) ||
empty($_POST['re_password']) ||
$_POST['password'] != $_POST['re_password']
){
// if a field is empty, or the passwords don't match make a message
error = '<p>';
if(empty($_POST['username'])){
$error .= 'No username given<br>';
}
if(empty($_POST['email'])){
$error .= 'No email given<br>';
}
if(empty($_POST['password'])){
$error .= 'No password given<br>';
}
if(empty($_POST['re_password'])){
$error .= 'You must re-type your password<br>';
}
if($_POST['password'] != $_POST['re_password']){
$error .= 'Passwords don\'t match<br>';
}
$error .= '</p>';
}
else{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password = $_POST['re_password'];
$query = mysqli_query(
$conn,"SELECT * FROM members WHERE username = '". $username ."' OR email = '". $email ."'");
if(mysqli_num_rows($query) > 0){
echo "Username or Email already exist";
}
else {
$sql = "INSERT INTO members (username, password, email)
VALUES
('$_POST[username]',
'$_POST[email]',
'$_POST[password]')";
if (mysqli_query($conn, $sql)) {
echo "Registered";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
}
}
if(isset($error)){
echo $error;
unset($error);
}
Upvotes: 0
Views: 340
Reputation: 72299
You need to change here only:--
if(mysqli_num_rows($query) > 0){
while ($row = mysqli_fetch_assoc($query)){
if(isset($row['username']) && !empty($row['username']) && $_POST['username'] ==$row['username'] )){
echo "Username already exist";
}
if(isset($row['password']) && !empty($row['password']) && $_POST['password'] ==$row['password'] )){
echo "Password already exist";
}
}
}
Note:- if your password have some encryption then you need to change password part condition accordingly (just third part of it). Also if i missed any wher indexes in writing let me know.
Upvotes: 2