Why Trying to get Property of non-object in?

Asked

Viewed 7,928 times

0

Guys I’m trying to return database data using this code:

//avoid Undefined variable
$errors = [];

if (Input::exists('post'))
{
    $validate = new Validate;

    $validation = $validate->check($_POST, array(
        'username' => array(
            'required' => true
        ),

        'password' => array(
            'required' => true
        )
    ));


    if ($validation->passed())
    {

        $data = $this->_model->get_member_hash(Input::get('username'));

        if (Password::password_verify(Input::get('password'), $data[0]->admin_password))
        {
            echo 'correct data';
        }
        else
        {
            echo 'incorrect data';
        }
    }
    else
    {
        $errors = $validation->errors();
    }

Only he’s returning to me these two mistakes

Notice: Undefined offset: 0

Notice: Trying to get Property of non-object in

What reason?

My model:

public function get_member_hash($username)
    {
        return $this->_db->read('SELECT * FROM ' . DATABASE_PREFIX . 'admins WHERE admin_email=:email OR admin_username=:username', array(
            ':email'    => $username,
            ':username' => $username,
        ));
    }

Validation class

<?php

/**
 * 
 */
class Input
{

    /**
     * 
     */
    public static function exists($type = 'post')
    {
        switch ($type)
        {
            case 'post':
                return (!empty($_POST)) ? true : false;
                break;

            case 'get':
                return (!empty($_GET)) ? true : false;
                break;

            default :
                return false;
                break;
        }
    }

    /**
     * 
     */
    public static function get($item)
    {
        if (isset($_POST[$item]))
        {
            return trim(strip_tags(filter_input(INPUT_POST, $item)));
        }
        else if (isset($_GET[$item]))
        {
            return trim(strip_tags(filter_input(INPUT_GET, $item)));
        }

        //By default return string
        return '';
    }
}

1 answer

-1

I don’t know what this method returns:

public function get_member_hash($username) { return $this->_db->read('SELECT * FROM ' . DATABASE_PREFIX . 'admins WHERE admin_email=:email OR admin_username=:username', array( ':email' => $username, ':username' => $username, )); }

In your code you treat it as if you’re sure it returns an array when you call $data[0]

The problem is that this method is not returning an array, because I believe that the query did not return even a value.

before calling $data[0] you need to make a check, like: if(is_array($data){ //faz algo } else { //não retornou nenhum valor }

Browser other questions tagged

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