开发者

PDO script to get the amount of rows not working?

I'm new to PDO PHP (just started today). I am attempting too write a login function, but it is returning false, even though i know the credentials are correct.

I think is is the attempt to get the amount of rows which is tripping the script up, can you help?

function check_login($email, $username, $password)
{
    $host = 'localhost';
    $port = 3306;
    $database = 'example';
    $username = 'root';
    $password = '';

    $dsn = "mysql:host=$host;port=$port;dbname=$database";
    $db = new PDO($dsn, $username, $password);
    $password = md5($password);

    $statement = $db->prepare("SELECT * FROM users WHERE email = ? or username = ? and password = ?");
    $statement->execute(array($email, $username, $password));

    while ($result = $statement->fetchObject()) {
        $sql = "SELECT count(*) FROM users WHERE email = ? or username = ? and password = ?";
        $result1 = $db->prepare($sql);
        $result1->execute(array($email, $username, $p开发者_开发知识库assword));
        $number_of_rows = $result1->fetchColumn();
        if ($number_of_rows == 1)
        {

            $_SESSION['login'] = true;
            $_SESSION['uid'] = $result->uid;
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }
}


  1. This:

    WHERE email = ? or username = ? and password = ?
    

    ... equals this:

    WHERE email = ? or (username = ? and password = ?)
    

    ... due to operator precedence. That means that if you validate with an e-mail address, you are not required to provide a valid password to log in.

  2. Once you've found out whether the user exists, you make a second query to count the number of matching users. The database table should not be able to hold duplicate users in the first place! Columns username and email should be defined as unique indexes.

  3. There's no point in using a while loop if it's going to return in the first iteration. It may work, but it's confusing.

This should be enough:

$statement = $db->prepare('SELECT uid FROM users WHERE (email = ? or username = ?) and password = ?');
$statement->execute(array($email, $username, $password));

if ($result = $statement->fetchObject()) {
    $_SESSION['login'] = true;
    $_SESSION['uid'] = $result->uid;
    return TRUE;
}else{
    return FALSE;
}

Edit: BTW, you should not be storing passwords in plain text. Countless sites have been hacked and their passwords stolen. Google for salted passwords.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜