How to login with username or email in PHP & MYSQL

In many social networking sites, they allow users to login with Username or Email using PHP. 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 with 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!

You May Also Like

Never Miss Any Web Tutorials, Guides, Tips and Free eBooks

Join Our Community Of 50,000+ Web Lovers and get a weekly newsletter in your inbox

 

I hate spam too. Unsubscribe at any time.

4 thoughts on “How to login with username or email in PHP & MYSQL”

  1. Why so complicated? You don’t need to create a function to determine if the user is logging in with an email address or a username. Just let MySQL handle it – here is an example:

    $name = $_POST[‘username’]; # userid can be an email address or a username
    $pass = md5($_POST[‘password’]); # Password

    $query = mysql_query(“SELECT * FROM `users` WHERE ‘$name’ IN (username, email) AND `password` = ‘$pass'”);

    Also, your example is vulnerable to SQL injection… At that point, you should start using MySQLi or PDO + prepared statements. Don’t use this example in a production environment…

    Reply

Leave a Comment