PDO脚本获取行数不起作用?

时间:2011-08-16 11:16:16

标签: php oop pdo

我是PDO PHP的新手(刚刚开始)。我正在尝试写一个登录函数,但它返回false,即使我知道凭据是正确的。

我认为是尝试获取绊倒脚本的行数,你能帮忙吗?

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, $password));
        $number_of_rows = $result1->fetchColumn();
        if ($number_of_rows == 1)
        {

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

1 个答案:

答案 0 :(得分:1)

  1. 此:

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

    ...等于:

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

    ...由于operator precedence。这意味着如果您使用电子邮件地址进行验证,则无需提供有效密码即可登录。

  2. 一旦确定用户是否存在,就会进行第二次查询以计算匹配用户的数量。数据库表不应该首先容纳重复的用户!列usernameemail应定义为唯一索引。

  3. 如果while循环在第一次迭代中转到return,则没有意义。它可能有用,但令人困惑。

  4. 这应该足够了:

    $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;
    }
    

    编辑:顺便说一句,您不应该以纯文本格式存储密码。无数网站遭到黑客入侵,密码被盗。谷歌的盐渍密码