In many social networking sites, they allow users to login with their Username or their Email Id. I would say this is the fantastic feature for whose all who forgot their usernames.

I strongly believe that most of the people will forgot their Usernames rather than Email id.

Here I am going to explain you about how to allow users to login using their username or email Id using PHP & MYSQL.

How to Login using Username or Email Id with PHP & MYSQL

In this project, I have used PHP’s native function called filter_var(). The filter_var() function filters a variable with the specified filter. Returns the filtered data on success or FALSE on failure

I wrote a small function that will find whether the user entered is email or username

function Is_email($user)
{
	//If the username input string is an e-mail, return true
	if(filter_var($user, FILTER_VALIDATE_EMAIL)) {
		return true;
	} else {
		return false;
	}
}

The above function will returns true If user has given Email Id or it returns false. Based on this we will easily switch the query

Database Structure

database_design

Complete Code

if($_POST['username'] != '' && $_POST['password'] != '')
{
$name = $_POST['username'];
$pass = md5($_POST['password']);

$check_email = Is_email($name);
if($check_email)
{
	// email & password combination
	$query = mysql_query("SELECT * FROM `users` WHERE `email` = '$name' AND `password` = '$pass'");
} else {
	// username & password combination
	$query = mysql_query("SELECT * FROM `users` WHERE `username` = '$name' AND `password` = '$pass'");
}
	$rows = mysql_num_rows($query);
	if($rows > 0)
	{
		//successfull login
	 	$_SESSION['username'] = $name;
	} else {
		$msg = "Invalid Login Credentials";
	}

mysql_close($connection);
} else {
$msg = "Please Provide All Details";
}

Please don’t forget to share and subscribe to latest updates of the blog. Comments and feedbacks are always welcome!

Thanks!

View Live Demo Download

If you enjoyed this article, Get email updates (It’s Free)
http://w3lessons.info/wp-content/uploads/2013/12/How-to-Login-using-Username-or-Email-Id-with-PHP-MYSQL.pnghttp://w3lessons.info/wp-content/uploads/2013/12/How-to-Login-using-Username-or-Email-Id-with-PHP-MYSQL-150x150.pngKarthikeyan KMysqlPHPnew techniques,php
In many social networking sites, they allow users to login with their Username or their Email Id. I would say this is the fantastic feature for whose all who forgot their usernames.I strongly believe that most of the people will forgot their Usernames rather than Email id.Here I am...