0

This is the code which shows the errors that have to be showed in my log in-system:

<?php

include 'session.php';

if (empty($_POST) === false) {
    $username = $_POST['username'];
    $password = $_POST['password'];

    if (empty($username) === true || empty($password) === true) {
        $errors[] = 'Please enter a username and password.';
    } else if (user_exists($username) === false) {
        $errors[] = 'The username or password is incorrect.';
    }
    print_r($errors);
}

?>

And this is the code that performs the query on the database, the function 'user_exists' which I used in the code above.

<?php

function user_exists($username) {
    $username = sanitize($username);
    return (mysql_result(mysql_query("SELECT COUNT(customerNumber) FROM customers WHERE username = '$username'"), 0) == 1) ? true : false;
}

?>

So when the username/password-combination is wrong, login.php should obviously say 'The username or password is incorrect.'. However, when I try to log in with the correct username and password (from my database), it also says 'The username or password is incorrect.'. So what is wrong with this code?

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • You aren't even checking the password against the records, although that isn't the cause of this problem. – Flosculus Apr 28 '15 at 15:47
  • 2
    Please, [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Apr 28 '15 at 16:06

1 Answers1

3

If i understand your problem correctly,this line makes you the real problem, it always returns false from here because your customer count on row 0 is not equal to 1, so every time it returns false.

return (mysql_result(mysql_query("
        SELECT COUNT(customerNumber) FROM customers WHERE 
        username = '$username'"), 0) == 1) ? true : false;

From PHP Manual User Notes

mysql_result() will throw E_WARNING if mysql_query returns 0 rows. This is unlike any of the mysql_fetch_* functions so be careful of this if you have E_WARNING turned on in error_reporting(). You might want to check mysql_num_rows() before calling mysql_result()

As Per Comment:

 function user_exists($username) {
    $username = sanitize($username);
    $result=mysql_result(mysql_query("SELECT COUNT(customerNumber) FROM customers WHERE username = '$username'"), 0);
    print $result; //see what it returns
    die();  //remove this line after your debugging.
    return ($result == 1) ? true : false;
}
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103