-2

I want build a query in php where user enters his email address and password and a row should be retrieved from database if the email and password matched from database. How can I do that? If any of the username or password is incorrect, a message should be printed accordingly.

Pankti
  • 411
  • 4
  • 13

2 Answers2

0

Remember, you should never store passwords as plain-text in database, please read about password hashing.

The simplest example:

function passwordHash($username, $password){
    $hash = $password;
    for($i = 0; $i < 10000; $i++){
        $hash = md5($hash . $username); // we use username as salt
    }
    return $hash;
}

$username = mysqli_real_escape_string($_POST['username']);
$hash = passwordHash($username, $_POST['password']);

$sql = "SELECT * FROM `users` WHERE username='$username' and password='$hash'";
$query = mysqli_query($sql);
if(mysqli_num_rows($query) != 0){
    // successfull login
}else{
    // login failed 
}

Of course you should make sign up form using the same hash function. Also I didn't initialize mysql connection.

Reptile
  • 21
  • 2
  • You shouldn't use MD5, please read: http://security.stackexchange.com/questions/19906/is-md5-considered-insecure PHP has its own function that does the job – Ivan Aug 14 '16 at 19:21
  • Use prepared statements! Read about SQL injections: http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Ivan Aug 14 '16 at 19:26
  • Guys, I wrote the simplest secure solution. Please notice, that I used 10000 iterations of md5 and used mysqli_real_escape_string. – Reptile Aug 14 '16 at 20:36
-1

I would go like this in pseudo-code :

if(authentication(email, password)) {
  phpQuery();
} else {
  alert();
}

Where the authentication() function compares email with password to grant access.

Ivan
  • 34,531
  • 8
  • 55
  • 100
pomeKRANK
  • 47
  • 7