In this article we discuss 2 Ways To Check if Email already exists Using PHP, to do that you also have to read about MySQL queries and syntax. On source code, we will use insert and select query to validate whether the email already exists or not.
Here is the list of 2 ways where we Check if Email already exists on the database Using PHP and MySQL,
- Set the email column as UNIQUE on the Database.
- Validate using MySQL select query with WHERE clause.
Set the Email Column as UNIQUE on the Database
To check if email already exists in the database using PHP we can use the UNIQUE column method. Where we set the email column as a UNIQUE column then MySQL will check and maintain the uniqueness of that field.
If you want to know more about SQL UNIQUE Key constraint check here: https://www.w3schools.com/sql/sql_unique.asp
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $con = mysqli_connect("localhost","root","","users"); if (isset($_POST['checkEmail'])) { $email = $_POST['email']; $insData = mysqli_query($con, "INSERT INTO `developers`(`email`) VALUES('$email')") or die(mysqli_error($con)); } ?> <form method="POST"> Email:<br> <input type="email" name="email" required><br><br> <button name="checkEmail">Validate Email</button> </form> |
Result:
If you try to insert the same email ID it gives you an error message, “Duplicate entry ‘mail@gmail.com’ for key ’email’“.
Here are some major things used by the above code to check if email already exists in PHP MySQLi,
- Set the “Email” column as unique on the Database.
- Use
die(mysqli_error($con)
MySQL error function with insert query to show the errors.
Validate Email using MySQL SELECT query with WHERE clause
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php $con = mysqli_connect("localhost","root","","users"); if (isset($_POST['register'])) { $email = $_POST['email']; $sql = "SELECT * FROM developers WHERE email='$email'"; $res = mysqli_query($db, $sql); if(mysqli_num_rows($res) > 0){ $email_error = "Sorry... email already taken"; }else{ $query = mysqli_query($con, "INSERT INTO `developers`(`email`) VALUES('$email')"); echo 'Saved!'; } } |
On the above code, we compare the user entered email with Database email using WHERE clause. After that we use
mysqli_num_rows()
to check the query result has any rows of data or not if data comes it means email matched with DB email which shows email already exists on DB.
Here are 2 best ways to check the email duplicacy with the Database. If you have any issues with implementation please let me know in the comment.
Also Check:
- 2 Ways to Open URL in New Tab Using JavaScript
- How to Embed PDF in Website Using HTML
- Set-up Firebase Project using Firebase Console
- Get List of Holidays Using Google Calendar API
Happy Coding..!
[…] 2 Ways To Check if Email already exists Using PHP […]
[…] 2 Ways To Check if Email already exists Using PHP […]
Hi,
Can you details explained this line:- mysqli_num_rows($res) > 0
Why greater than 0?