Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

login with username or email address in php

Tags:

php

mysql

I am trying to create a login with username or email

My code is:

$username=$_REQUEST['login'];
$email=$_REQUEST['login'];
$password=$_REQUEST['password'];

if($username && $password) {
  $query="select * from  user_db where username='$username'  and password='$password'";
} else if ($email && $password) {
  $query="select * from  user_db where email='$email' and password='$password'";
}

Login with username is success but login with email is not working. Please help me!

like image 292
SureshKumar Vegesna Avatar asked May 02 '12 17:05

SureshKumar Vegesna


2 Answers

The login parameter is the same for both email and username. Not exactly incorrect if you have a single login box that accepts either.

You could put the condition in the query itself if you're not sure if it's an email or username.

$login=$_REQUEST['login'];
$query = "select * from  user_db where ( username='$login' OR email = '$login') and password='$password'"

Edit: A PDO-like solution is much more preferred nowadays as the above is subject to SQL injection. The logic stays the same, but you'd have it look something like this:

$query = "
    SET @username = :username
    SELECT * FROM user_db
       WHERE ( username = @username OR email = @username) 
       AND password = :password
";

$statement = $pdoObject->prepare($query);
$statement->bindValue(":username", $login, PDO::PARAM_STR);
$statement->bindValue(":password", $password, PDO::PARAM_STR);
$statement->execute();
like image 153
Recognizer Avatar answered Sep 30 '22 08:09

Recognizer


You are setting the same value to two variables, and then using an if/else. Both if statements are equivalent.

You need to figure out if $_REQUEST[login] contains a valid email address, and if so use the email field of the database. Otherwise, use the username field.

Also, you should not be putting variables directly into the query. Use prepared statements.

like image 41
gcochard Avatar answered Sep 30 '22 08:09

gcochard