Cannot use Object of type stdClass as array

Asked

Viewed 3,945 times

1

I made a code to check if the user and email are already existing, but when the user exists it returns the following error:

Fatal error: Fatal error: Cannot use Object of type stdClass as array

$query_check_user_name = $this->db->prepare('SELECT username, mail FROM users WHERE username= :user_name OR
mail = :user_email');
$query_check_user_name->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$query_check_user_name->bindValue(':user_email', $user_email, PDO::PARAM_STR);
$query_check_user_name->execute();
$result = $query_check_user_name->fetchAll();

if (count($result) > 0) {
    for ($i = 0; $i < count($result); $i++) {
        $this->errors[] = ($result[$i]['user_name'] == $user_name) ? MESSAGE_USERNAME_EXISTS : MESSAGE_EMAIL_ALREADY_EXISTS;
    }
} else {
}
  • I answered in the can, but forgot the classic question: "Which line did this error occur"?

  • 1

    Another tip: Don’t use the for to iterate with arrays, especially with that count($result) being called every check for :)

1 answer

2


Try this

 $query_check_user_name->fetchAll(PDO::FETCH_ASSOC);

PHP usually returns this error when you have any object (as long as you don’t implement the interface ArrayAccess) and tries to access it as array.

Example

$objeto = new stdClass;

$objeto->nome = 'Wallace';

$objeto['nome']; // Fatal Error:  Cannot use object of type stdClass as array

Browser other questions tagged

You are not signed in. Login or sign up in order to post.