Validate the username and email if already exists. The validation of username and email exist is a restriction to the user for duplicate remove.
If already exist an email then show the error message and then check if the email id already exists then show the error message. If the email and username did not match (exists) in the table then insert the data into a MySQL database table (or do something according to your need).To check (validate ) username and email we will use mysqli_num_rows() inbuilt function of PHP. The mysqli_num_rows() function is used to return the number of rows.
If the user fills the complete form and clicks on the submit button then an error message will be visible if the username and email already exist. If the username and email id do not exist, then insert the data into the MySQL table. (or run your code )
Check username and email already exists in PHP and MYSQL
Now let's come to the implementation.
'
check username and email already exists
<?php
$sql="select * from users where (username='$username' or email='$email');";
$res=mysqli_query($mysqli,$sql);
if (mysqli_num_rows($res) > 0) {
$row = mysqli_fetch_assoc($res);
if($email==isset($row['email']))
{
echo "email already exists";
}
if($username==isset($row['username']))
{
echo "username already exists";
}
}
else{
//do your insert code here or do something (run your code)
}
?>
In the above PHP script, we have restricted a user can register only one time using one username and email id.
1. MYSQL query selects the table data (username and email) from the table.
2. mysqli_num_rows() function returns the number of rows.
3. mysqli_fetch_assoc() function fetches a result row as an associative array..
4. if condition for check the email already exists.
5. if condition for check the username already exists.
6.echo the error message if username or email already exists .
7. If the username or email did not exists then run your code (according to your project need )
Recommended Posts:-