How to use data from a Codeigniter session

0

Hello, I have the following code where I log in and I save the data in Array . I want to know what is the way to get data in a view.

function check_database($pwd){
    $username = $this->input->post('username');
    $result = $this->m->login($username, $pwd);
    if ($result){
        foreach($result as $row){
            $sess_array = array(
                'Codigo' => $row->Codigo,
                'Nombre' => $row->Nombre,
            );
            $this->session->set_userdata('logged_in', $sess_array);
        }    
        return TRUE;
    } else {
        $this->form_validation->set_message('check_database', 'Usuario Invalido');
        return false;
    }
}

Here I charge the view:

public function menu(){
    if (!$this->session->userdata('logged_in')) {
        redirect('main/index', 'refresh');
    }    
    $this->load->view('dashboard');
}

View:

<?php include ('header.php'): ?>
//Aqui ver los datos de la persona logueada
<?php include ('footer.php'): ?>
    
asked by MoteCL 05.06.2018 в 23:02
source

1 answer

4

To obtain the session variables, there are 3 methods according to the official documentation, which are the following:

$name = $_SESSION['name'];
$name = $this->session->name
$name = $this->session->userdata('name');

In your case it would be as follows:
    Controller:

function check_database($pwd){
    $username = $this->input->post('username');
    $result = $this->m->login($username, $pwd);

    if ($result){
        foreach($result as $row){
            $sess_array = array(
                'Codigo' => $row->Codigo,
                'Nombre' => $row->Nombre,
                'logged_in' => TRUE);
            $this->session->set_userdata($sess_array);
        }
        return TRUE;
    } else {
        $this->form_validation->set_message('check_database', 'Usuario Invalido');
        return false;
    }
}

Load view:

public function menu(){
    if (!$this->session->userdata('logged_in')) {
        redirect('main/index', 'refresh');
    }
    $this->load->view('dashboard');
}

View:

<?php include ('header.php'): ?>

$codigo = $this->session->userdata('Codigo');
$nombre = $this->session->userdata('Nombre');

echo 'Datos del usuario';
echo 'Código: '.$codigo;
echo 'Nombre: '.$nombre;

<?php include ('footer.php'): ?>

Official documentation:

  

link

    
answered by 05.06.2018 / 23:18
source