Reputation: 262
I am trying to show logged User Name in every view page by storing data in session.
But i have to write same two line in every function.. I am getting user data but Is there other ways to do This. Because i Think repeating same code is not too well.
Controller
So, This is my index function where i have email and also a model which is used to get user data from database.
function index() {
$email = $this->session->userdata('email');
$data['details'] = $this->Perfect_mdl->get_login_user_detail($email);
$data['items_data'] = $this->Visa_mdl->get_items_name();
$data['title'] = "Hotels";
$this->load->view('include/header',$data);
$this->load->view('hotels/visa',$data);
$this->load->view('include/footer');
}
Second function
Now, Here Same thing i have to do for showing User Name
function visa_dashboard($item_id = NULL) {
$email = $this->session->userdata('email');
$data['details'] = $this->Perfect_mdl->get_login_user_detail($email);
$data['title'] = "Company Lists";
$result = $this->Visa_mdl->get_items_company_list($item_id);
$result1 = $this->Visa_mdl->get_items_name_in_dash($item_id);
$data['items'] = $result1;
$data['items_company_data'] = $result;
$data['items_data'] = $this->Visa_mdl->get_items_name();
// $data['items_company_data'] = $this->Visa_mdl->get_items_company_list($id);
$this->load->view('include/header',$data);
$this->load->view('hotels/dashboard',$data);
$this->load->view('include/footer');
}
I am very new in Codeigniter . How to do this ?
Upvotes: 0
Views: 2059
Reputation: 2375
The best solution is to store frequent required data in session !
then define a user class but to make it more sample create a custom helper instead in helper/custom_helper.php
define a function like
function login_username(){
$CI = &get_instance()
$username = $CI->session->userdata('username');
if (!empty($username)) {
return $username;
}else{
$email = $CI->session->userdata('email');
//here you can load model or run query to get userdata or
// username
//then set it in session for next time you need
$CI->load->model('Perfect_mdl');
$userdata = $CI->Perfect_mdl->get_login_user_detail($email);
$CI->session->set_userdata(array('username'=>$userdata['username']));
return $userdata['username'];
}
}
autoload custom helper in config/autoload
now just call it where you want it
echo login_username();
Upvotes: 0
Reputation: 41
Vishal you can use $this->email
and more to display in any function of welcome controller, pass that value from your method to view on
$this->load->view('view1',$data['session'])`;
Hope it will solve your problem.
Upvotes: 0
Reputation: 1585
Put the two lines in the controller's constructor and it's available in all the methods.
<?php
class Welcome extends CI_Controller {
public function __construct()
{
$this->load->model('perfect_mdl');
$this->email = $this->session->userdata('email');
$this->data['details'] = $this->Perfect_mdl->get_login_user_detail($email);
}
}
Upvotes: 1