0

I have recently starting following some coding tutorials for PHP CodeIgniter and I have run into a bit of a snag for my login and registration system. The registration works perfectly, accessing the database and creating accounts but there is a problem with my login code that I can not work my head around.

I receive the following error:

A PHP Error was encountered Severity: Notice

Message: Trying to get property 'email' of non-object

Filename: controllers/Auth.php

Line Number: 23

Backtrace:

File: /opt/lampp/htdocs/application/controllers/Auth.php Line: 23 Function: _error_handler

File: /opt/lampp/htdocs/index.php Line: 315 Function: require_once

The code for the following is:

    <?php

class Auth extends CI_Controller{

    public function login()
    {
        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
        if($this->form_validation->run() == TRUE) {

            $username = $_POST['username'];
            $password = md5($_POST['password']);

            //check user in db

            $this->db->select('*');
            $this->db->from('users');
            $this->db->where(array('username'=>$username, 'password'=>$password));
            $query = $this->db->get();

            $user = $query->row();

            if ($user->email){
                $this->session->set_flashdata("success", "You are logged in.");

                $_SESSION['user_logged'] = TRUE;
                $_SESSION['username'] = $user->username;

                //redirect to profile page

                redirect("user/profile", "refresh");
            } else {
                $this->session->set_flashdata("error", "NO such account exists");
                //redirect("auth/login", "refresh");
            }

        }       
        $this->load->view('login');
    }

public function register()
    {
        if(isset($_POST['register'])) {
            $this->form_validation->set_rules('username', 'Username', 'required');
            $this->form_validation->set_rules('email', 'Email', 'required');
            $this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
            $this->form_validation->set_rules('password', 'Confirm Password', 'required|min_length[5]|matches[password]');

            if($this->form_validation->run() == TRUE) {
                //echo 'form validated';

                //add user in database

                $data = array(
                    'username'=>$_POST['username'],
                    'email'=>$_POST['email'],
                    'password'=> md5($_POST['password'])
                );
                $this->db->insert('users', $data);

                $this->session->set_flashdata("success", "Your account has been registered");
                redirect("auth/register", "refresh");
            }
        }
        $this->load->view('register');
    }
} 

?>

Any help would be appreciated and if anymore code that I have used for this tutorial is needed for a solution, just let me know.

Thank you.

JDoxx
  • 11
  • 2
  • instead of `if ($user->email){` you should write `if ($user){` because you are trying to get a property of an object which doesnt even exists - if `$user` is null - then there is no property `email` – Atural Apr 08 '18 at 13:05
  • Error say you are trying access as an object on non-object. check if your query is returning result or not. – prasanna puttaswamy Apr 08 '18 at 13:06
  • make sure about user data is exists on database. $query = $this->db->get(); if ($query->num_rows() > 0) { $user = $query->row(); } – Emre Savcı Apr 08 '18 at 13:11
  • `var_dump($user)` the value of `$user` and make sure it is not array instead of object and also check if email exists in it. If it was array instead of object try getting the value like this: `$user['email']` – TheDevWay Apr 08 '18 at 13:12
  • Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – Vickel Apr 08 '18 at 13:35

1 Answers1

0

You will get that kindof error when the result object from the database is returning no rows hence an empty stdClass and thus you will not be able to access any properties. The correct way of doing this is to check that num_rows() is equal to 1 (e.g. there should only be one user with that name and password).

public function login() {
    $this->form_validation->set_rules('username', 'Username', 'required');
    $this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
    if ($this->form_validation->run() == TRUE) {

        $username = $_POST['username'];
        /**
         * Do not md5 your passwords!
         * Use password_hash and password_verify!!
         */
        $password = md5($_POST['password']); // DO NOT MD5 your passwords!

        //check user in db
        // this should be in a model!
        $this->db->select('*');
        $this->db->from('users');
        $this->db->where(array('username' => $username, 'password' => $password));
        $query = $this->db->get();

        if ($query->num_rows() == 1) {
            $user = $query->row();
            $this->session->set_flashdata("success", "You are logged in.");

            $_SESSION['user_logged'] = TRUE;
            $_SESSION['username'] = $user->username;

            //redirect to profile page
            redirect("user/profile", "refresh");
        } else {
            $this->session->set_flashdata("error", "NO such account exists");
            //redirect("auth/login", "refresh");
        }
    }
    $this->load->view('login');
}

Generally you should get into the habit of checking if num_rows() > 0 before ever using result() row() .etc. because you can never be 100% sure that the data will be returned.

For example:

//model

function get_users() {
     $query = $this->db->get('users');
     if ($query->num_rows() == 0) {
          return null;
     }
     return $query->result();
}

// controller

function something() {
    $users = $this->model->get_users();
    if (is_null($users)) {
         exit('no users');
    }
    print_r($users);
}
Alex
  • 9,215
  • 8
  • 39
  • 82