验证用户名和密码:在非对象上调用成员函数fetchAll()

时间:2015-04-23 15:22:43

标签: php pdo

我似乎无法弄清楚在这做什么。我试图获取用户的用户名和密码,并将其与数据库中的哈希密码进行比较,以验证其凭据并将其登录。

以下是代码:

session_start();  // Start Session

include 'db.php';
$dbh = new PDO("mysql:host=$dbhost;dbname=$database_name", $dbusername, $dbpasswd);

// Conver to simple variables
$username = $_POST['username'];
$password = $_POST['password'];

/*if((!$username) || (!$password)){
    echo "Please enter ALL of the information! <br />";
    include 'login.html';
    exit();*/
//}

$sql = $dbh->prepare("SELECT * FROM users WHERE username=?");
$result = $sql->execute([$username]);
$users = $result->fetchAll();
// $sql = "SELECT * FROM users WHERE username = ?";
// $stmt = $dbh->prepare($sql);
// $result = $stmt->execute([$username]);
// $users = $result->fetchAll();
if (isset($users[0])) {
    if (password_verify($password, $users[0]->password)) {
        //Register some session variables!  
        session_register('email_address');
        $_SESSION["username"] = $username;
        $_SESSION["email_address"] = $email_address;
        //session_register('special_user');
        $_SESSION["user_level"] = $user_level;


        mysql_query("UPDATE users SET last_login=now() WHERE userid='$userid'");

        header("Location: daily_picks.php");
    } else {
        echo "Invalid Credentials";
        include 'login.html';
    }
} else {
        echo "Invalid Credentials";
        include 'login.html';
}

在非对象中获取对成员函数fetchAll()的错误调用。 。

1 个答案:

答案 0 :(得分:2)

您的对象是$sql

所以:

$result = $sql->execute([$username]);
$users = $result->fetchAll();

应该是:

$result = $sql->execute([$username]);
$users = $sql->fetchAll();

请注意execute()返回一个布尔值。