-1

I get this error message:

Fatal error: Cannot use object of type stdClass as array

Code:

if(isset($_POST['anmelden']))
{
    $email = $_POST['email'];
    $passwort = $_POST['passwort'];

    $statement = $pdo->prepare("SELECT * FROM hwvor_nutzer WHERE nutzer_email = :email");
    $result = $statement->execute(array('email' => $email));
    $user = $statement->fetch();

    if($user !== false && password_verify($passwort, $user['passwort'])) 
    {
        $_SESSION['userid'] = $user['id'];
        die('Login erfolgreich. Weiter zum <a href="nutzerberich.php">internen Bereich</a>');
    } 
    else 
    {
        $errorMessage = "E-Mail oder Passwort war ungültig<br>";
    }
}
Striezel
  • 3,693
  • 7
  • 23
  • 37
Freddy
  • 1
  • 3

2 Answers2

0

You might want to check the value of $result before fetching data, just in case the query failed. I guess the problem is caused by $user['passwort'] in the line

if($user !== false && password_verify($passwort, $user['passwort']))

If the query failed, then $user = $statement->fetch(); will not assign an array to $user, but something else which cannot be handled as array.

Furthermore, I believe the line

$result = $statement->execute(array('email' => $email));

should be changed to

$result = $statement->execute(array(':email' => $email));

Notice the extra :, it seems to be required, looking at the examples on php.net.

Striezel
  • 3,693
  • 7
  • 23
  • 37
  • What exactly does not work? Please provide some more information. Have you added the `:`? Did you check the value of `$result`? Did you dump the content of `$user`? If you did, what are their values? – Striezel Jun 16 '18 at 09:40
0

It sounds like your PDO is defaulting to fetching an object rather than an array, try calling fetch with an argument to fetch as an array implicitly, you should also try dumping out the resulting object that you are receiving to see what it is.

$user = $result->fetch(PDO::FETCH_ASSOC);

Trey
  • 5,480
  • 4
  • 23
  • 30
  • According to the [documentation on php.net](http://php.net/manual/en/pdostatement.fetch.php) the default is `PDO::FETCH_BOTH`, which returns an array indexed by both column name and 0-indexed column number as returned in the result set . – Striezel Jun 15 '18 at 16:07
  • According to the documentation, the default is `PDO::ATTR_DEFAULT_FETCH_MODE (which defaults to PDO::FETCH_BOTH).` I have no idea what else on his system might change `PDO::ATTR_DEFAULT_FETCH_MODE`, and fetch always returns false in the event of any error, if the result is an object it seems the fetch mode is not the original default – Trey Jun 15 '18 at 16:09
  • what doesn't work? @Striezel made an excellent point about the `:` in your key... if you want additional help you'll need to provide us with additional information, did you try printing the value of `$user`? or `$result` for that matter? If so what was the value? – Trey Jun 15 '18 at 18:31