3

I have implemented the login logic in an MVC application; I want to see if the user has filled the username and passowrd incorrectly and if so I want to show a notifictaion in the view; so I'm passing this information via $data['er']; but for some reason it is not catching this data:

Please let me know if my question is clear or not; and if any clarification is needed, please let me know which part is ambiguous

My code:

class Login extends CI_Controller {

    public function __construct() {
        parent::__construct();
         $GLOBALS['er'] = False;
    }



    public function index() {

        $data['er']=$GLOBALS['er'];
        $data['main_content'] = 'login_form';
        $this->load->view('includes/template', $data);
    }

    public function validate_credentials() {

        $this->load->model('user_model');
        $query = $this->user_model->validate();
        if ($query) {
            $data = array(
                'username' => $this->input->post('username'),
            );
            $this->session->set_userdata($data);
            redirect('project/members_area');
        } else {
            $GLOBALS['er'] = TRUE;
            $this->index();

        }
    }

} 
user385729
  • 1,924
  • 9
  • 29
  • 42

1 Answers1

7

Don't use GLOBALS you can just use a private variable in your class.

  • Create the variable above your __construct function like private $er
  • In your __contruct function set the default value
  • Set and get in your public function using $this->er

Implemented in your code:

class Login extends CI_Controller {

    private $er;

    public function __construct() {
        parent::__construct();
        $this->er = FALSE;
    }

    public function index() {
        $data['er']= $this->er;
        $data['main_content'] = 'login_form';
        $this->load->view('includes/template', $data);
    }

    public function validate_credentials() {
        $this->load->model('user_model');
        $query = $this->user_model->validate();
        if ($query) {
            $data = array(
                'username' => $this->input->post('username'),
            );
            $this->session->set_userdata($data);
            redirect('pmpBulletin/members_area');
            //die(here);
        } else {
            $this->er = TRUE;
            $this->index();
        }
    }
} 
doitlikejustin
  • 6,293
  • 2
  • 40
  • 68
  • OP ask for global variable usage, not local class variable. Take in consideration that the var, can be requested in any other places around the App. Seems to be already open one thread about this https://stackoverflow.com/questions/17013397/codeigniter-best-place-to-declare-global-variable – Kadaiser Jan 17 '22 at 09:48