Devon February 2016

PHP Fatal error: Call to a member function fetchAll() on a non-object in pdo login

I've been working on a web app for a client, and came across this error when building the database login code.

The config.php code

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

And the login.php code

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

The Register.php works, and adds the fields to the database, but I'll add to make sure I'm not missing something, since it is trying to access the database to verify a record.

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]);

Answers


Vishal February 2016

You are using the wrong object($result) to fetch

You need to use $stmt Do like this

$users = $stmt->fetchAll();

also, you need to pass the variable as an array before that

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

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

Post Status

Asked in February 2016
Viewed 2,117 times
Voted 9
Answered 1 times

Search




Leave an answer