PHP致命错误:在pdo登录中的非对象上调用成员函数fetchAll()

时间:2016-02-08 21:26:41

标签: php mysql pdo

我一直在为客户端开发Web应用程序,并在构建数据库登录代码时遇到此错误。

config.php代码

php try {
    // Create connection
    $dbh = new PDO("mysql:host=" . $localhost . ";dbname=" . $database, $username, $dbpassword);
} catch (PDOException $e) {
    // Echo error message if the connection fails
    echo 'Connection failed: ' . $e->getMessage();
    exit;
}

login.php代码

require 'config.php';
$sql = "SELECT * FROM `Users` WHERE `email` = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['email']]);
$users = $result->fetchAll();

if (isset($users[0])) {
    if (password_verify($_POST['password'], $users[0]->password)) {
        // valid login
        include 'dashboard.php';
    } 
    else {
        // invalid password
        echo "<p class=''>The password you entered is Incorrect. Please try again.</p>";
    }
} 
else {
    // invalid email
    echo "<p class=''>We're sorry, That email is not in our Records. Please Check the spelling and try again.</p>";
}

Register.php有效,并将字段添加到数据库中,但我会添加以确保我没有遗漏任何内容,因为它正在尝试访问数据库以验证记录。

require 'config.php';
require 'lib/password.php';

$company = $_POST["company"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_BCRYPT);

$stmt = $dbh->prepare("insert into Users(id,company,email,password) VALUES (?,?,?,?)");
$stmt->execute([$id, $company, $email, $hash]);

1 个答案:

答案 0 :(得分:-1)

您使用了错误的对象($ result)来获取

您需要使用$ stmt 这样做

$users = $stmt->fetchAll();

另外,您需要在此之前将变量作为数组传递

$stmt->execute(array($_POST['email']));

http://php.net/manual/en/pdostatement.fetchall.php